【问题标题】:javascript prototype chaining - get parent of parent of [duplicate]javascript原型链接-获取[重复]的父级的父级
【发布时间】:2013-06-24 03:31:04
【问题描述】:

我一直在阅读有关 javascript 原型链接的内容,据我所知,有一个全局 Object.prototype 是其他原型的基础,例如 Array.prototype,它可以作为另一个原型的基础。就像基于类的 OOP 中的继承一样。没关系。

现在,我想检查和比较不同对象的原型。如果Array 的原型是基于Object.prototype 的,我想Array.prototype.prototype 这样的东西应该是可能的。但它是未定义的:

> Array.prototype.prototype
undefined

当我输入 __proto__ 而不是 prototype 时,我得到:

> Array.__proto__
[Function: Empty]
> Object.__proto__
[Function: Empty]
> Array.__proto__.__proto__
{}

(控制台输出取自 nodejs)。我有以下问题:

  • 如何访问原型的“父原型”?
  • prototype__proto__ 有什么区别?

【问题讨论】:

    标签: javascript prototype


    【解决方案1】:

    我相信您正在寻找:

    Object.getPrototypeOf(Array.prototype);
    // The same as Object.prototype
    

    (这是一个 ES5 特性,not compatible with some older browsers)。

    prototype和__proto__有什么区别

    prototype 属性始终属于构造函数(如 ObjectArray 和自定义构造函数)。 __proto__ 属性存在于使用此类构造函数创建的实例上,并指向与 constructor.prototype 相同的对象。

    例如:

    function MyClass(){}
    var myObj = new MyClass();
    myObj.__proto__ === MyClass.prototype; // true
    

    在你给出的例子中,Array.__proto__ 实际上是构造函数的原型对象——而不是它的prototype 属性。这就是为什么它是[Function: Empty],因为Array 是一个函数,是默认Function 构造函数的一个实例。某些特定数组实例的__proto__Array.prototype 相同:

    var arr = [];
    arr.__proto__ === Array.prototype; // true
    

    【讨论】:

    • 不完全是。 Array.prototype 本身是“与某些数组实例的 __proto__ 相同”,而不是它的原型。
    • @Bergi 如果这是关于我的第一个代码块上的注释,那么您是对的。已删除。
    猜你喜欢
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多