溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

js中Object.create怎么用

發(fā)布時間:2021-10-08 09:29:43 來源:億速云 閱讀:109 作者:小新 欄目:開發(fā)技術

小編給大家分享一下js中Object.create怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1、用Object.create()方法創(chuàng)建新對象,并使用現(xiàn)有對象提供新對象的proto。

2、提供兩個參數(shù),第一個是新創(chuàng)建的原型對象,第二個是為新創(chuàng)建的對象添加屬性的對象。

實例

// father 對象
let father = {
    name: 'father',
    friend: ['abby', 'bob']
}
 
// 生成新實例對象 child1
let child1 = Object.create(father)
 
// 更改值類型屬性
child1.name = '修改了name'
console.log(child1.name) //修改了name
 
// 更改引用類型值
child1.friend.push('chely')
console.log(child1.friend) //[ 'abby', 'bob', 'chely' ]
 
// 生成新實例對象 child2
let child2 = Object.create(father)
console.log(child2.name) //father
console.log(child2.friend) //[ 'abby', 'bob', 'chely' ]

知識點擴展:

Object.create()創(chuàng)建方法實例

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();
// expected output: "My name is Matthew. Am I human? true"

運行結果

> "My name is Matthew. Am I human? true"

以上是“js中Object.create怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI