在学习过程当中对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);
Father.prototype.constructor = Father,这里修正了的Father的constructor。咱们知道prototype下的constructor属性返回对建立此对象的函数的引用。
1、不修正时
Father.constructor = function Function(),Father.prototype.constructor = function Person(),这里引出
一个题外话,为何Father.constructor !== Father.prototype.constructor。是全部对象(包括函数)都有的,它才叫作对象的原型,原型链就是靠它造成的。
只有函数(准确地说是构造函数)才有的。它跟原型链没有关系。它的做用是:构造函数new对象的时候,告诉构造函数新建立的对象的原型是谁。
1. _proto_2. prototype
Father.constructor,是从Father的原型链查找属性,也就是__,由于Father继承的是Function(){},而Function(){}的constructor就是它本身
因此Father.constructor = function Function();
proto__
为何Father.prototype.constructor 是 function Person(),首先Father.prototype = new Person('Beijin');当咱们用new
运算符会产生如下步骤:
也就是说(new Person('Beijin')).__proto__ === Person.prototype //true
前面咱们说过new Person('Beijin')对象是没有prototype的,prototype只有函数才有;Father.prototype.constructor将会沿着new Person('Beijin')的
原型链向下查找constructor,new Person('Beijin')没有constructor就去它的__proto__找,由于(new Person('Beijin')).__proto__ === Person.prototype
而Person.prototype.constructor == function Person(),因此 Father.prototype.constructor == Person.prototype.constructor //function Person()
当咱们var one = new Father(25) 时 ,one.constructor = Father.prototype.constructor,因此one.constructor指向function Person(),

2、修正时
当咱们加上Father.prototype.constructor = Father;对象one的原型链变成

显而易见,one.constructor = Father.prototype.constructor = function Father();
3、做用
var man; (function(){ function Father (name) { this.name = name; } Father.prototype.sayName= function () { console.log(this.name); } man = new Father('aoyo'); })() man.sayName();//aoyo console.log(Father); //Father is not defined
由于Father在闭包中,当咱们想对Father类增长方法时能够经过函数
man.constructor.prototype.sayAge = function(age){ console.log(age); } man.sayAge('20'); //20
若是不进行修正,咱们的方法将会添加到Person类,而不是Father类。学习