【问题标题】:Javascript using constructor.prototype to visit superclass member fails?Javascript使用constructor.prototype访问超类成员失败?
【发布时间】:2016-12-16 10:22:06
【问题描述】:

我有一个小代码sn-p:

function father(){
    this.id=10
}
function child(){}
console.log(child.prototype.constructor);//[Function: child]
child.prototype=new father();
//child.prototype.constructor = child; // key line
var son=new child();
console.log(child.prototype.constructor);//[Function: father]
console.log(son.constructor.prototype.id);//undefined.

正如代码所示,我使用原型链来创建“儿子”对象。 但是最后一行打印出来

"undefined". 

这对我来说很奇怪。 child.prototype.constructor是[Function:father],而“id”其实是“father”的一个属性,为什么打印undefined?

如果我取消注释

    child.prototype.constructor = child; // key line

然后它按我的预期打印“10”。对我来说,是否有关键线的区别在于 child.prototype.constructor 是“孩子”还是“父亲”。但是 'id' 是父属性,为什么需要在我的代码中设置关键行?

谢谢。

【问题讨论】:

  • id 既不是father 的属性,也不是father.prototype 的属性。这是father 实例的属性!
  • 我试图用一些糟糕的图片来回答它:)

标签: javascript constructor prototype undefined superclass


【解决方案1】:

步骤 1)

function father(){
    this.id=10
}
function child(){}

看起来像

这种情况下console.log(child.prototype.constructor);//[Function: child] 会按您的预期工作

第 2 步)child.prototype=new father();

现在您在这里看到,原来的child.prototype 丢失了,child.prototype.constructor 也丢失了。您从 father 创建了一个对象并将该对象用作 child.prototype

第 3 步)var son=new child();

现在console.log(child.prototype.constructor);//[Function: father] 很容易理解。

我们如何到达那里? son.__proto__.__proto__.constructor.

现在,考虑相同的图像

console.log(son.constructor.prototype.id);//undefined.这里发生了什么? son.constructor 只不过是 fatherson.constructor.prototype 只不过是 father.prototype ,它没有属性名称 id

注意: son.constructorson.__proto__.__proto__.constructor

现在你取消注释 child.prototype.constructor = child; 会发生什么?

您正在向child.prototype 添加一个constructor 属性,在这种情况下,当您说son.constructor 这意味着childson.constructor.prototype 只不过是child.prototype,它确实有一个属性名称id值为 10。

抱歉所有图片和不好的解释!!

【讨论】:

  • 我只是找不到用语言表达的方法。干得好。
  • 很好的插图。希望它们的尺寸没有缩小,焦点没有模糊。
  • 好吧,好吧,好吧,这是我自 stackoverflow 之旅以来得到的最佳答案之一。 Oxi 做得好,非常感谢您的解释!投票!
  • @Troskyvs : 很高兴我能帮上忙 :)
【解决方案2】:

实际上,您正在覆盖子 function() 的原型对象,因此内部 proto 链接丢失了。

function father(){
    this.id=10
}
function child(){}
console.log(child.prototype.constructor);//[Function: child]
child.prototype=new father();
child.__proto__ = father;
var son=new child();
console.log(child.prototype.constructor);//[Function: father]
console.log(son.id);//10

【讨论】:

  • a) 不要使用__proto__ b) 它不起作用 c) 没有丢失的链接
  • 那如何解释我的问题呢?谢谢。
  • proto 永远不应该直接使用。 proto 是 Firefox/Chrome 提供的非标准属性。在其他浏览器中,该属性仍然存在于内部,但它是隐藏的。
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 2023-04-04
  • 2013-01-09
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多