簡體   English   中英

Array.prototype.isPrototypeOf 和 A​​rray.isPrototypeOf 有什么區別?

[英]What the difference between Array.prototype.isPrototypeOf and Array.isPrototypeOf?

我想知道Array.prototype.isPrototypeOfArray.isPrototypeOf什么區別我認為它應該工作相同,因為我認為它會引用相同的方法isPrototypeOf但看起來我錯了。 有人可以向我解釋為什么這樣工作嗎?

 const exampleArray = [1, 2, 3]; console.log(Array.prototype.isPrototypeOf(exampleArray)); console.log(Array.isPrototypeOf(exampleArray)); // Why this statement returns false ?

這些都是對Object.prototype.isPrototypeOf()引用,它檢查它被調用的對象是否在傳遞參數的原型鏈中。

對於exampleArray ,原型鏈是這樣的:

Object.prototype <- Array.prototype <- exampleArray instance

見片段:

 const exampleArray = [1, 2, 3]; console.log( Object.getPrototypeOf(exampleArray) === Array.prototype, Object.getPrototypeOf(Array.prototype) === Object.prototype );

Array構造函數- window.Array - 不在原型鏈中,因此isPrototypeOf返回false

如果類擴展了Array ,或者如果通過Object.create將其設置為新對象的內部原型,則 Array 構造函數只會讓isPrototypeOf返回true ,例如:

 class ExtendedArray extends Array {} console.log(Array.isPrototypeOf(ExtendedArray)); const somethingWeird = Object.create(Array); console.log(Array.isPrototypeOf(somethingWeird));

為了完整Object.prototype , Array 構造函數 - 作為一個函數 - 繼承自Function.prototype ,后者繼承自Object.prototype

 console.log( Object.getPrototypeOf(Array) === Function.prototype, Object.getPrototypeOf(Function.prototype) === Object.prototype );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM