function Person(area){
this.type = 'person';
this.area = area;
}
Person.prototype.sayArea = function(){
console.log(this.area);
}
var Father = function(age){
this.age = age;
}
Father.prototype = new Person('Beijin');
console.log(Person.prototype.constructor) //function person()
console.log(Father.prototype.constructor); //function person()
Father.prototype.constructor = Father;//修正
console.log(Father.prototype.constructor); //function father()
var one = new father(25);
看到一些资料,对原型继承进行一个修正,让子对象的prototype.constructor
正确指向自身。我在火狐测试,在没有Father.prototype.constructor = Father
时,one实例的第一个__proto__
是没有constructor
属性的,需要向第二个__proto__
查找constructor
属性。
问题是:这样的修正有必要吗?好像修不修正使用都是一样的呀;我把它修改成一个自定义的函数Father.prototype.constructor = foo()
好像对使用也没影响,constructor
属性仅仅起到一个标识构造函数的作用吗?
首先,
constructor
是原型对象上的一个属性,默认指向这个原型的构造函数。当你没有进行斧正的时候,
由
Father
构建出来的对象one
的构造函数指向是Person
,而不是你new
它的时候用的构造函数Father
。这就导致了原型链的错乱。因为在
这一步的时候,原型指向了一个新对象,这个新对象的
constructor
指向的是Person
。这一步的修正,也就相当于在
new Person()
的对象上添加一个constructor
属性,重新指向Father
,保证原型链的正确。