Object.create()和new 創建對象的區別


Object.create()方法是ECMAScript5中新增的,用來規范化原型式繼承的。
這個方法接收兩個參數,一個是用作新對象原型的對象,和一個為新對象定義額外屬性的(可選)對象。

var person = { name : "Nicholas", friends : ["John", "Jane"] // 引用類型值屬性共享 } var onePerson = Object.create(person); // onePerson繼承person對象 onePerson.name = "Greg"; onePerson.friends.push("Mike"); console.log(onePerson.name); // Greg console.log(onePerson.friends); // ["John", "Jane", "Mike"] var anotherPerson = Object.create(person); console.log(anotherPerson.name); // Nicholas anotherPerson.friends.push("Jacky"); console.log(anotherPerson.friends); // ["John", "Jane", "Mike", "Jacky"] // 第二個參數對象格式與Object.defineProperties()方法的第二個參數格式相同 var theOtherPerson = Object.create(person, { name : { configurable : false, // 不可修改 value : "Greg" } }); console.log(theOtherPerson.name); // Greg theOtherPerson.name = "Bob"; // 失效 console.log(theOtherPerson.name); // Greg

new Object()方法的實質是,使用引用類型Object的構造函數創建了一個新的實例,這個實例擁有Object默認的方法如toString、toLocaleString等。

示例基於JavaScript高級程序設計第三版進行了一些修改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM