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属性仅仅起到一个标识构造函数的作用吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先,
constructor是原型对象上的一个属性,默认指向这个原型的构造函数。当你没有进行斧正的时候,
由
Father构建出来的对象one的构造函数指向是Person,而不是你new它的时候用的构造函数Father。这就导致了原型链的错乱。因为在
这一步的时候,原型指向了一个新对象,这个新对象的
constructor指向的是Person。这一步的修正,也就相当于在
new Person()的对象上添加一个constructor属性,重新指向Father,保证原型链的正确。修正后,
new Foo.prototype.constructor()相当于new Foo()。我也就知道这么一点,等大神补充吧。
ES5和ES6中的继承
这里有个图,比较直观