【问题标题】:is Object.getPrototypeOf() same as Object.constructor.prototype in Javascript?Object.getPrototypeOf() 是否与 JavaScript 中的 Object.constructor.prototype 相同?
【发布时间】:2011-12-22 22:01:31
【问题描述】:

Object.getPrototypeOf(obj)obj.constructor.prototype 有区别吗?还是这两个引用同一个东西?

【问题讨论】:

  • 您可以为有用的问题和答案投票,也可以接受解决您自己问题的答案。这有助于组织 SO,也是对帮助过你的人的小小奖励。
  • @missingno 他的问题到目前为止还是很有趣的……
  • @ŠimeVidas:尽管如此,他仍然值得“0%”样板评论:P

标签: javascript inheritance constructor prototype-programming


【解决方案1】:

它返回内部[[Prototype]] 值。

例如:

var o = Object.create(null);
Object.getPrototypeOf(o); // null
o.constructor.prototype; // error

var p = {};
var o = Object.create(p);
Object.getPrototypeOf(o); // p
o.constructor.prototype; // Object.prototype

o.constructor.prototype 仅适用于通过new ConstructorFunction 创建的对象或您手动设置Prototype.prototype.constructor === Prototype 关系的对象。

【讨论】:

    【解决方案2】:

    。特别是,对象的 constructor 属性并不总是设置为您认为“正确”的值。

    getPrototypeOf 有效但 .constructor.prototype 无效的示例:

    function F() { }
    F.prototype = {
       foo: "bar"
    };
    
    var obj = new F();
    
    assert.equal(obj.constructor.prototype, Object.prototype);
    assert.equal(Object.getPrototypeOf(obj), F.prototype);
    

    对于典型的原型继承场景也失败了:

    // G prototypally inherits from F
    function G() { }
    G.prototype = Object.create(F.prototype);
    // or: G.prototype = new F();
    
    var obj2 = new G();
    
    assert.equal(obj2.constructor.prototype, Object.prototype);
    assert.equal(Object.getPrototypeOf(obj2), G.prototype);
    assert.equal(Object.getPrototypeOf(Object.getPrototypeOf(obj2)), F.prototype);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多