关于原型链中constructor、prototype及__proto__的问题

最近看到一个关于原型链的问题,回顾一下原型链的知识点。

function person(name)
{
    this.name = name;
    this.showME = function()
    {
    alert(this.name);
    }
};

person.prototype.form = function()
{
    alert('i come form prototype')
}
var father = new Person('JS');
alert(father.constructor);
function Subper()
{
...
}
SubPer.prototype = father;
Sub.protptype.constructor = subper;
var son = new Subper();
son.showMe();  //JS
son.from();   //i come form prototype
alert(father.constructor);  //function Subper(){}
alert(son.constructor);  //function SubPer() {}
alert(SubPer.prototype.constructor);   //function SubPer() {}




说说为什么father.constructor 为什么是function Subper(){}。
首先father.constructor 不是 father 自身的属性,而是原型链上的,即father的prototype原型中。类似通过 father.__proto__.constructor 这样来找到 constructor 的值。就这个问题而言,father.__proto__ 指向的是 Person.prototype。Subper.prototype = father ,不是复制了 father 对象,而是把 Subper.prototype 指向了 father,所以对Subper.prototype 的修改会影响到 father 的值。

此时Subper.prototype.constructor属性实际就是father.__proto__.constructor。因此当Subper.prototype.constructor = Subper 时,son.constructor = father.__proto__.constructor =person.prototype.constrctor = Subper。

再看看这张图一切都明朗了。

clipboard.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值