constructor

  • 所有的函数都有一个prototype属性,它是一个对象。
  • prototype有一个constructor的属性,默认是指向prototype所在的构造函数。
  • constructor会被实例继承。他的作用就是表名某个实例对象是由哪个构造函数产生的。如下,p是没有constructor 的,他的constructor 就指向P
function P(){}
const p = new P();
p.constructor === P // true

利用constructor属性,我们便可以通过一个实例对象,创建另一个实例对象。如下

function P(){}
const p = new P();
const p2 = new p.constructor();
p2 instanceof P // true

以上p是P的一个实例对象,通过p的constructor构造函数方法来声明p2,那么p2也是P的一个实例


constructor是表示原型和实例关联关系的一个属性。所以当修改原型对象的时候,也会修改constructor。防止出现引用错误

function Person(name) {
  this.name = name;
}
Person.prototype.constructor === Person // true
Person.prototype = {
  method: function () {}
};
Person.prototype.constructor === Person // false
Person.prototype.constructor === Object // true

如上,我们在重写了Person的prototype原型对象后,没有了constructor,那么Person.prototype.constructor就不再指向Person,但是我们可以通过Person.prototype.constructor = Person强行指回去。在原型继承中会用到


function P(){}
// 坏的写法
P.prototype = {
  method1: function (...) { ... },
  // ...
};
// 好的写法
P.prototype = {
  constructor: C,
  method1: function (...) { ... },
  // ...
};
// 更好的写法
P.prototype.method1 = function (...) { ... };

以上三种都是操作P的原型对象,第一个显然会导致constructor指向错误,第二个不会导致错误但是不够灵活,所以普遍推崇第三种写法


当我们不知道某个实例的原型对象时可以通过constructor的name属性来获取

function Foo() {}
var f = new Foo();
f.constructor.name // "Foo"

完结,撒花

你可能感兴趣的:(constructor)