首页 > js中constructor的实际作用?

js中constructor的实际作用?

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是原型对象上的一个属性,默认指向这个原型的构造函数。

当你没有进行斧正的时候,

var one = new Father(25)
console.log(one.constructor) // function Person() {}

Father构建出来的对象one的构造函数指向是Person,而不是你new它的时候用的构造函数Father。这就导致了原型链的错乱。

因为在

Father.prototype = new Person('Beijin');

这一步的时候,原型指向了一个新对象,这个新对象的constructor指向的是Person

Father.prototype.constructor = Father; // 修正

这一步的修正,也就相当于在new Person()的对象上添加一个constructor属性,重新指向Father,保证原型链的正确。


// 比如一个构造函数:
function Foo() {  }

// 声明一个函数后,默认就生成下面这条语句。
Foo.prototype.constructor === Foo    // true

修正后,new Foo.prototype.constructor()相当于new Foo()
我也就知道这么一点,等大神补充吧。


ES5和ES6中的继承
这里有个图,比较直观

【热门文章】
【热门文章】