Объект в javascript — это неупорядоченный список примитивных типов данных.
let myObj = { name: “Vini” } You can access the property of an object via myObj[“name”]
Различные способы создания объекта javascript
- Литерал объекта
// This is an empty object initialized using the object literal notation var myBooks = {};// 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"); } }
2. Конструктор объектов
var mango = new Object (); mango.color = "yellow"; mango.shape= "round"; mango.sweetness = 8; mango.howSweetAmI = function () { console.log("Hmm Hmm Good"); }
3. Шаблон конструктора для создания объектов
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); }); }}
Шаблон прототипа для создания объектов
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); }