javascript - js中constructor的实际作用?
巴扎黑
巴扎黑 2017-04-10 16:59:20
[JavaScript讨论组]
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属性仅仅起到一个标识构造函数的作用吗?

巴扎黑
巴扎黑

全部回复(3)
PHP中文网

首先,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,保证原型链的正确。

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

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

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

巴扎黑

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号