关于javascript:js中constructor的作用

6次阅读

共计 2205 个字符,预计需要花费 6 分钟才能阅读完成。

在学习过程中对 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 属性返回对创立此对象的函数的援用。

一、不修改时
Father.constructor = function Function(),Father.prototype.constructor = function Person(),这里引出
一个题外话,为什么 Father.constructor!== Father.prototype.constructor。
1. _proto_是所有对象 (包含函数) 都有的,它才叫做 对象的原型 ,原型链就是靠它造成的。
2. prototype 只有函数 (精确地说是构造函数) 才有的。它跟原型链没有关系。它的作用是:构造函数 new 对象的时候,通知构造函数新创建的对象的原型是谁。

Father.constructor,是从 Father 的原型链查找属性,也就是__proto__, 因为 Father 继承的是 Function(){},而 Function(){}的 constructor 就是它本人
所以 Father.constructor = function Function();

为什么 Father.prototype.constructor 是 function Person(),首先 Father.prototype = new Person(‘Beijin’); 当咱们用 new
运算符会产生以下步骤:

  1. var obj={}; 也就是说,初始化一个对象 obj。
  2. obj.__proto__=a.prototype;
  3. a.call(obj); 也就是说结构 obj,也能够称之为初始化 obj。

也就是说 (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(),

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

不言而喻,one.constructor = Father.prototype.constructor = function Father();
三、作用 </pre>

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 类。
正文完
 0