【发布时间】: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