javascript 中 constructor 的那些事儿

有哪些 constructor

在 javascript 中,涉及到 constructor 的概念有三个

  • 构造函数可被称为一个 constructor
  • 所有的对象有一个 constructor 属性
  • ES6 语法中有一个 constructor 关键字

一脸懵逼…

构造函数 —— constructor

1
2
3
function Person(name) {
this.name = name;
}

这就是 javascript 中的构造函数,又可称为一个构造器(constructor)

对象的 constructor 属性

Object.prototype.constructor 属性返回了一个引用,这个引用指向产生实例的构造函数

Returns a reference to the Object constructor function that created the instance object

1
2
3
4
5
6
function Person(name) {
this.name = name;
}

var man = new Person('xwill');
console.log(man.constructor === Person); // 通过 new 关键字生成的对象,它的 constructor 属性指向构造函数本身
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var o = new Object;
var str = new String('hello');
var arr = [];

var cat = {
name: 'mark'
}

console.log(o.constructor === Object); // true
console.log(str.constructor === String); // true
console.log(arr.constructor === Array); //true

// 通过字面量定义的对象,它的 constructor 指向 Object
console.log(cat.constructor === Object);

constructor 属性会被覆盖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Person(name) {
this.name = name;
}

function Animal(name) {
this.name = name;
}

var man = new Person('xwill');

console.log(man.constructor === Person); // true
// constructor 属性的引用对象变成了 Animal
man.constructor = Animal;
console.log(man.constructor === Animal); // true
console.log(man.constructor === Person); // false

这就是最好不用 constructor 确定实例(instance)所属类型的原因
判断实例类型,用 instanceof 关键字