1) // object constructor
var mango = new Object (); mango.color = "yellow"; mango.shape= "round"; mango.sweetness = 8; mango.howSweetAmI = function () { console.log("Hmm Hmm Good"); }
2) // object literal
// This is an object with 4 items, again using object literal var mango = { color: "yellow", shape: "round", sweetness: 8, howSweetAmI: function () { console.log("Hmm Hmm Good"); } }
3) // constructor pattern
function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) { this.color = theColor; this.sweetness = theSweetness; this.fruitName = theFruitName; this.nativeToLand = theNativeToLand; this.showName = function () { console.log("This is a " + this.fruitName); } this.nativeTo = function () { this.nativeToLand.forEach(function (eachCountry) { console.log("Grown in:" + eachCountry); }); } } var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
4) // using prototype pattern
function Fruit () { } Fruit.prototype.color = "Yellow"; Fruit.prototype.sweetness = 7; Fruit.prototype.fruitName = "Generic Fruit"; Fruit.prototype.nativeToLand = "USA"; Fruit.prototype.showName = function () { console.log("This is a " + this.fruitName); } Fruit.prototype.nativeTo = function () { console.log("Grown in:" + this.nativeToLand); } var mangoFruit = new Fruit ();
5) // using Object.create()
var superHuman = { usePower: function () { console.log(this.superPower + "!"); } }; var banshee = Object.create(superHuman, { name: { value: "Silver Banshee" }, superPower: { value: "sonic wail" } }); // Outputs: "sonic wail!" banshee.usePower();