繁体   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