創(chuàng)建新對象

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"}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容