我想知道有什么区别Array.prototype.isPrototypeOf,Array.isPrototypeOf我认为它应该工作相同,因为我认为它会引用相同的方法,isPrototypeOf但看起来我错了。有人可以向我解释为什么这样工作吗?
const exampleArray = [1, 2, 3];
console.log(Array.prototype.isPrototypeOf(exampleArray));
console.log(Array.isPrototypeOf(exampleArray)); // Why this statement returns false ?Run Code Online (Sandbox Code Playgroud)
Cer*_*nce 24
这些都是对 的引用
Object.prototype.isPrototypeOf(),它检查它所调用的对象是否在传递参数的原型链中。
对于exampleArray,原型链是这样的:
Object.prototype <- Array.prototype <- exampleArray instance
Run Code Online (Sandbox Code Playgroud)
见片段:
const exampleArray = [1, 2, 3];
console.log(
Object.getPrototypeOf(exampleArray) === Array.prototype,
Object.getPrototypeOf(Array.prototype) === Object.prototype
);Run Code Online (Sandbox Code Playgroud)
Array构造函数- window.Array- 不在原型链中,因此isPrototypeOf返回false。
Array 构造函数只有在类扩展时才会isPrototypeOf返回,或者如果通过 将其设置为新对象的内部原型,例如:trueArrayObject.create
class ExtendedArray extends Array {}
console.log(Array.isPrototypeOf(ExtendedArray));
const somethingWeird = Object.create(Array);
console.log(Array.isPrototypeOf(somethingWeird));Run Code Online (Sandbox Code Playgroud)
为完整起见,Array 构造函数 - 作为一个函数 - 继承自Function.prototype,它继承自Object.prototype:
console.log(
Object.getPrototypeOf(Array) === Function.prototype,
Object.getPrototypeOf(Function.prototype) === Object.prototype
);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
665 次 |
| 最近记录: |