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

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

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 的值。spa

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

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

clipboard.png

相关文章
相关标签/搜索