Object.create()

Object.create()方法創建一個新對象,使用現有的對象來提供新創建的對象的_proto_。

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
console.log('me', me)

在這裏插入圖片描述
Object.create(proto, [propertiesObject])
參數
proto:新創建對象的原型對象
propertiesObject:可選,如果沒有指定爲undefined,則是要添加到新對象的可枚舉屬性(即其自身定義的屬性,而不是其原型鏈上的屬性)對象的屬性描述符以及相應的屬性名稱,這些屬性對應Object.defineProperties()的第二個參數
返回值
一個新對象,帶着指定的原型對象和屬性

注意:如果propertiesObject參數不是null或一個對象,則拋出一個TypeError異常

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章