[英]Why the prototype not equal with Object.create()
根據官方演示 The Object.create() method creates a new object with the specified prototype object and properties.
用下面的代碼,為什么原型不相等?
function Shape() {} function Rectangle() {} Rectangle.prototype = Object.create(Shape.prototype); console.log(`${Shape.prototype === Rectangle.prototype}`) // false
為什么Shape.prototype === Rectangle.prototype
為false
在兩個對象引用(名稱)(例如Rectangle.prototype
和Shape.prototype
)上使用===
時,您正在測試兩個引用是否實際上引用了同一對象。 如果您有兩個不同的對象恰好在其中包含相同的值,或者有兩個不同的對象(其中一個是另一個的原型),則它們將不相等。
您對Object.create()
調用將創建一個新對象 。 它永遠不會比其他任何對象都相等。 Rectangle.prototype
是您剛剛創建的全新對象。 它不是對與Shape.prototype
相同的對象的Shape.prototype
。 Rectangle.prototype
的原型是Shape.prototype
,但這並不能使它們成為同一對象。 因此他們將比較不平等。
相比之下,假設您已這樣做:
Rectangle.prototype = Shape.prototype;
現在Rectangle.prototype
和Shape.prototype
都是對同一個對象的引用,因為=
運算符就是這樣做的。 與Object.create()
不同, =
運算符不會創建新對象,而只會創建對同一對象的新引用。 如果然后使用===
比較它們,則它們將比較相等,因為這兩個名稱從字面上指的是同一對象。
從MDN :
Object.create()方法使用指定的原型對象和屬性創建一個新對象。
Rectangle.prototype
是一個對象,其原型為Shape.prototype
。 也就是說, Rectangle.prototype != Shape.prototype
。
另一方面:
function Shape() {} function Rectangle() {} Rectangle.prototype = Object.create(Shape.prototype) // true console.log(Object.getPrototypeOf(Rectangle.prototype) == Shape.prototype)
另外,您可以使用instanceof
驗證給定的對象是否是某些原型的實例:
function Shape() {} function Rectangle() {} Rectangle.prototype = Object.create(Shape.prototype) console.log(Rectangle.prototype instanceof Shape)
您在這里有一個中間對象。 Object.create具有此簽名
Object.create(proto)
其中proto
是對象,應該是新創建對象的原型。
Rectangle.prototype
是指原型已設置為Shape.prototype
的對象。 當使用===
您將比較它們的引用,這是不同的,所以為什么會出錯。
看到可視化
------- -----
Rectangle.prototype -> | | | |
|proto| ------> -----
------- ^
|
Shape.prototype ----------------------------
您不能使用===或==比較對象。 您需要編寫函數以檢查每個單個屬性以及屬性數量以檢查對象的相等性。 你可以在這里讀到它 -
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.