1、字面量
var obj = {}
2、構(gòu)造函數(shù)
· 函數(shù)名建議首字母大寫
· 使用 this 將傳入函數(shù)的值賦給對象的屬性
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var kenscar = new Car("Nissan", "300ZX", 1992);//實例化對象
實例對象添加屬性不會影響到構(gòu)造函數(shù)。因此構(gòu)造函數(shù)中可以設(shè)置公用的屬性,特有屬性在各自的實例化對象中添加
kenscar.color = "black";
console.log(kenscar); // {make: "Nissan", model: "300ZX", year: 1992, color: "black"}
console.log(Car)
/* Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}*/
在不修改構(gòu)造函數(shù)的前提下,使用prototype添加新的公用屬性。
Car.prototype.color = null;
var newCar = new Car();
var newCar2 = new Car();
console.log(newCar);
console.log(newCar2);

image.png

image.png
因為js的繼承和原型鏈原理,默認(rèn)瀏覽器會層層向上查詢。所以通過prototype添加的屬性,可以在實例化對象中使用
newCar.color直接訪問到,而不需要通過newCar._proto_.color來訪問。
3、Object.create(指定原型對象[,屬性及描述])
允許為創(chuàng)建的對象指定原型對象
let a = {
name: 'hello'
}
let o = Object.create(a)
let b = {}
console.log(o.__proto__); // {name: "hello"}
console.log(b.__proto__); // {constructor: ?, __defineGetter__: ?, …}
第二個參數(shù)可選
var o;
// 創(chuàng)建一個原型為null的空對象
o = Object.create(null, {
// foo會成為所創(chuàng)建對象的數(shù)據(jù)屬性
foo: {
writable:true,
configurable:true,
value: "hello"
},
// bar會成為所創(chuàng)建對象的訪問器屬性
bar: {
configurable: false,
get: function() { return 10 },
set: function(value) {
console.log("Setting `o.bar` to", value);
}
}
});
console.log(o); // {foo: "hello"}