关于原型链中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

评论

暂无评论