在學習過程當中對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類。學習