基本用法

JavaScript 语言中,生成实例对象的传统方法是通过构造函数。下面是一个例子。

1
2
3
4
5
6
7
8
9
10
function Point(x, y) {
this.x = x
this.y = y
}

Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')'
}

var p = new Point(1, 2)

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

1
2
3
4
5
6
7
8
9
10
class Point {
constructor(x, y) {
this.x = x
this.y = y
}

toString() {
return '(' + this.x + ', ' + this.y + ')'
}
}

上面代码定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。也就是说,ES5 的构造函数Point,对应 ES6 的Point类的构造方法。

ES6 的类,完全可以看作构造函数的另一种写法。

1
2
3
4
5
6
class Point {
// ...
}

typeof Point // "function"
Point === Point.prototype.constructor // true

上面代码表明,类的数据类型就是函数,类本身就指向构造函数。

使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。

1
2
3
4
5
6
7
8
class Bar {
doStuff() {
console.log('stuff')
}
}

var b = new Bar()
b.doStuff() // "stuff"

构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。

constructor 方法

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。

1
2
3
4
5
6
class Point {}

// 等同于
class Point {
constructor() {}
}

上面代码中,定义了一个空的类Point,JavaScript 引擎会自动为它添加一个空的constructor方法。

constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

1
2
3
4
5
6
7
8
class Foo {
constructor() {
return Object.create(null)
}
}

new Foo() instanceof Foo
// false

上面代码中,constructor函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。

类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。

1
2
3
4
5
6
7
8
class Foo {
constructor() {
return Object.create(null)
}
}

Foo()
// TypeError: Class constructor Foo cannot be invoked without 'new'

name 属性

由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被Class继承,包括name属性。

1
2
class Point {}
Point.name // "Point"

name属性总是返回紧跟在class关键字后面的类名。

参考资料:

《ES6 标准入门》(第 3 版) 阮一峰著