最近看到一個關於原型鏈的問題,回顧一下原型鏈的知識點。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