代码之家  ›  专栏  ›  技术社区  ›  Krzysztof Kaczyński

有什么区别Array.prototype.isPrototypeOf以及Array.isPrototypeOf?

  •  6
  • Krzysztof Kaczyński  · 技术社区  · 5 年前

    我想知道这两者之间有什么区别 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 ?
    1 回复  |  直到 5 年前
        1
  •  7
  •   CertainPerformance    5 年前

    它们都是指 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
    );

    阵列 构造函数 window.Array -不在原型链中,所以 isPrototypeOf 退货 false

    isPrototypeOf true Array ,或者如果它被设置为新对象的内部原型,则通过 Object.create ,例如:

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

    Function.prototype ,继承自 Object.prototype :

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