Class 的基本语法

简介

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

  1. function Point(x, y) {
  2. this.x = x;
  3. this.y = y;
  4. }
  5. Point.prototype.toString = function () {
  6. return '(' + this.x + ', ' + this.y + ')';
  7. };
  8. var p = new Point(1, 2);

上面这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,很容易让新学习这门语言的程序员感到困惑。

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

基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6 的class改写,就是下面这样。

  1. //定义类
  2. class Point {
  3. constructor(x, y) {
  4. this.x = x;
  5. this.y = y;
  6. }
  7. toString() {
  8. return '(' + this.x + ', ' + this.y + ')';
  9. }
  10. }

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

Point类除了构造方法,还定义了一个toString方法。注意,定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

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

  1. class Point {
  2. // ...
  3. }
  4. typeof Point // "function"
  5. Point === Point.prototype.constructor // true

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

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

  1. class Bar {
  2. doStuff() {
  3. console.log('stuff');
  4. }
  5. }
  6. var b = new Bar();
  7. b.doStuff() // "stuff"

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

  1. class Point {
  2. constructor() {
  3. // ...
  4. }
  5. toString() {
  6. // ...
  7. }
  8. toValue() {
  9. // ...
  10. }
  11. }
  12. // 等同于
  13. Point.prototype = {
  14. constructor() {},
  15. toString() {},
  16. toValue() {},
  17. };

在类的实例上面调用方法,其实就是调用原型上的方法。

  1. class B {}
  2. let b = new B();
  3. b.constructor === B.prototype.constructor // true

上面代码中,bB类的实例,它的constructor方法就是B类原型的constructor方法。

由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。

  1. class Point {
  2. constructor(){
  3. // ...
  4. }
  5. }
  6. Object.assign(Point.prototype, {
  7. toString(){},
  8. toValue(){}
  9. });

prototype对象的constructor属性,直接指向“类”的本身,这与 ES5 的行为是一致的。

  1. Point.prototype.constructor === Point // true

另外,类的内部所有定义的方法,都是不可枚举的(non-enumerable)。

  1. class Point {
  2. constructor(x, y) {
  3. // ...
  4. }
  5. toString() {
  6. // ...
  7. }
  8. }
  9. Object.keys(Point.prototype)
  10. // []
  11. Object.getOwnPropertyNames(Point.prototype)
  12. // ["constructor","toString"]

上面代码中,toString方法是Point类内部定义的方法,它是不可枚举的。这一点与 ES5 的行为不一致。

  1. var Point = function (x, y) {
  2. // ...
  3. };
  4. Point.prototype.toString = function() {
  5. // ...
  6. };
  7. Object.keys(Point.prototype)
  8. // ["toString"]
  9. Object.getOwnPropertyNames(Point.prototype)
  10. // ["constructor","toString"]

上面代码采用 ES5 的写法,toString方法就是可枚举的。

类的属性名,可以采用表达式。

  1. let methodName = 'getArea';
  2. class Square {
  3. constructor(length) {
  4. // ...
  5. }
  6. [methodName]() {
  7. // ...
  8. }
  9. }

上面代码中,Square类的方法名getArea,是从表达式得到的。

严格模式

类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。

考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式。

constructor 方法

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

  1. class Point {
  2. }
  3. // 等同于
  4. class Point {
  5. constructor() {}
  6. }

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

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

  1. class Foo {
  2. constructor() {
  3. return Object.create(null);
  4. }
  5. }
  6. new Foo() instanceof Foo
  7. // false

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

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

  1. class Foo {
  2. constructor() {
  3. return Object.create(null);
  4. }
  5. }
  6. Foo()
  7. // TypeError: Class constructor Foo cannot be invoked without 'new'

类的实例对象

生成类的实例对象的写法,与 ES5 完全一样,也是使用new命令。前面说过,如果忘记加上new,像函数那样调用Class,将会报错。

  1. class Point {
  2. // ...
  3. }
  4. // 报错
  5. var point = Point(2, 3);
  6. // 正确
  7. var point = new Point(2, 3);

与 ES5 一样,实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。

  1. //定义类
  2. class Point {
  3. constructor(x, y) {
  4. this.x = x;
  5. this.y = y;
  6. }
  7. toString() {
  8. return '(' + this.x + ', ' + this.y + ')';
  9. }
  10. }
  11. var point = new Point(2, 3);
  12. point.toString() // (2, 3)
  13. point.hasOwnProperty('x') // true
  14. point.hasOwnProperty('y') // true
  15. point.hasOwnProperty('toString') // false
  16. point.__proto__.hasOwnProperty('toString') // true

上面代码中,xy都是实例对象point自身的属性(因为定义在this变量上),所以hasOwnProperty方法返回true,而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty方法返回false。这些都与 ES5 的行为保持一致。

与 ES5 一样,类的所有实例共享一个原型对象。

  1. var p1 = new Point(2,3);
  2. var p2 = new Point(3,2);
  3. p1.__proto__ === p2.__proto__
  4. //true

上面代码中,p1p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。

这也意味着,可以通过实例的__proto__属性为“类”添加方法。

__proto__ 并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目前很多现代浏览器的 JS 引擎中都提供了这个私有属性,但依旧不建议在生产中使用该属性,避免对环境产生依赖。生产环境中,我们可以使用 Object.getPrototypeOf 方法来获取实例对象的原型,然后再来为原型添加方法/属性。

  1. var p1 = new Point(2,3);
  2. var p2 = new Point(3,2);
  3. p1.__proto__.printName = function () { return 'Oops' };
  4. p1.printName() // "Oops"
  5. p2.printName() // "Oops"
  6. var p3 = new Point(4,2);
  7. p3.printName() // "Oops"

上面代码在p1的原型上添加了一个printName方法,由于p1的原型就是p2的原型,因此p2也可以调用这个方法。而且,此后新建的实例p3也可以调用这个方法。这意味着,使用实例的__proto__属性改写原型,必须相当谨慎,不推荐使用,因为这会改变“类”的原始定义,影响到所有实例。

Class 表达式

与函数一样,类也可以使用表达式的形式定义。

  1. const MyClass = class Me {
  2. getClassName() {
  3. return Me.name;
  4. }
  5. };

上面代码使用表达式定义了一个类。需要注意的是,这个类的名字是MyClass而不是MeMe只在 Class 的内部代码可用,指代当前类。

  1. let inst = new MyClass();
  2. inst.getClassName() // Me
  3. Me.name // ReferenceError: Me is not defined

上面代码表示,Me只在 Class 内部有定义。

如果类的内部没用到的话,可以省略Me,也就是可以写成下面的形式。

  1. const MyClass = class { /* ... */ };

采用 Class 表达式,可以写出立即执行的 Class。

  1. let person = new class {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. sayName() {
  6. console.log(this.name);
  7. }
  8. }('张三');
  9. person.sayName(); // "张三"

上面代码中,person是一个立即执行的类的实例。

不存在变量提升

类不存在变量提升(hoist),这一点与 ES5 完全不同。

  1. new Foo(); // ReferenceError
  2. class Foo {}

上面代码中,Foo类使用在前,定义在后,这样会报错,因为 ES6 不会把类的声明提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。

  1. {
  2. let Foo = class {};
  3. class Bar extends Foo {
  4. }
  5. }

上面的代码不会报错,因为Bar继承Foo的时候,Foo已经有定义了。但是,如果存在class的提升,上面代码就会报错,因为class会被提升到代码头部,而let命令是不提升的,所以导致Bar继承Foo的时候,Foo还没有定义。

私有方法和私有属性

现有的方法

私有方法是常见需求,但 ES6 不提供,只能通过变通方法模拟实现。

一种做法是在命名上加以区别。

  1. class Widget {
  2. // 公有方法
  3. foo (baz) {
  4. this._bar(baz);
  5. }
  6. // 私有方法
  7. _bar(baz) {
  8. return this.snaf = baz;
  9. }
  10. // ...
  11. }

上面代码中,_bar方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。

另一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。

  1. class Widget {
  2. foo (baz) {
  3. bar.call(this, baz);
  4. }
  5. // ...
  6. }
  7. function bar(baz) {
  8. return this.snaf = baz;
  9. }

上面代码中,foo是公有方法,内部调用了bar.call(this, baz)。这使得bar实际上成为了当前模块的私有方法。

还有一种方法是利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。

  1. const bar = Symbol('bar');
  2. const snaf = Symbol('snaf');
  3. export default class myClass{
  4. // 公有方法
  5. foo(baz) {
  6. this[bar](baz);
  7. }
  8. // 私有方法
  9. [bar](baz) {
  10. return this[snaf] = baz;
  11. }
  12. // ...
  13. };

上面代码中,barsnaf都是Symbol值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。

私有属性的提案

与私有方法一样,ES6 不支持私有属性。目前,有一个提案,为class加了私有属性。方法是在属性名之前,使用#表示。

  1. class Point {
  2. #x;
  3. constructor(x = 0) {
  4. #x = +x; // 写成 this.#x 亦可
  5. }
  6. get x() { return #x }
  7. set x(value) { #x = +value }
  8. }

上面代码中,#x就表示私有属性x,在Point类之外是读取不到这个属性的。还可以看到,私有属性与实例的属性是可以同名的(比如,#xget x())。

私有属性可以指定初始值,在构造函数执行时进行初始化。

  1. class Point {
  2. #x = 0;
  3. constructor() {
  4. #x; // 0
  5. }
  6. }

之所以要引入一个新的前缀#表示私有属性,而没有采用private关键字,是因为 JavaScript 是一门动态语言,使用独立的符号似乎是唯一的可靠方法,能够准确地区分一种属性是否为私有属性。另外,Ruby 语言使用@表示私有属性,ES6 没有用这个符号而使用#,是因为@已经被留给了 Decorator。

该提案只规定了私有属性的写法。但是,很自然地,它也可以用来写私有方法。

  1. class Foo {
  2. #a;
  3. #b;
  4. #sum() { return #a + #b; }
  5. printSum() { console.log(#sum()); }
  6. constructor(a, b) { #a = a; #b = b; }
  7. }

上面代码中,#sum()就是一个私有方法。

另外,私有属性也可以设置 getter 和 setter 方法。

  1. class Counter {
  2. #xValue = 0;
  3. get #x() { return #xValue; }
  4. set #x(value) {
  5. this.#xValue = value;
  6. }
  7. constructor() {
  8. super();
  9. // ...
  10. }
  11. }

上面代码中,#x是一个私有属性,它的读写都通过get #x()set #x()来完成。

this 的指向

类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。

  1. class Logger {
  2. printName(name = 'there') {
  3. this.print(`Hello ${name}`);
  4. }
  5. print(text) {
  6. console.log(text);
  7. }
  8. }
  9. const logger = new Logger();
  10. const { printName } = logger;
  11. printName(); // TypeError: Cannot read property 'print' of undefined

上面代码中,printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print方法而导致报错。

一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。

  1. class Logger {
  2. constructor() {
  3. this.printName = this.printName.bind(this);
  4. }
  5. // ...
  6. }

另一种解决方法是使用箭头函数。

  1. class Logger {
  2. constructor() {
  3. this.printName = (name = 'there') => {
  4. this.print(`Hello ${name}`);
  5. };
  6. }
  7. // ...
  8. }

还有一种解决方法是使用Proxy,获取方法的时候,自动绑定this

  1. function selfish (target) {
  2. const cache = new WeakMap();
  3. const handler = {
  4. get (target, key) {
  5. const value = Reflect.get(target, key);
  6. if (typeof value !== 'function') {
  7. return value;
  8. }
  9. if (!cache.has(value)) {
  10. cache.set(value, value.bind(target));
  11. }
  12. return cache.get(value);
  13. }
  14. };
  15. const proxy = new Proxy(target, handler);
  16. return proxy;
  17. }
  18. const logger = selfish(new Logger());

name 属性

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

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

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

Class 的取值函数(getter)和存值函数(setter)

与 ES5 一样,在“类”的内部可以使用getset关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

  1. class MyClass {
  2. constructor() {
  3. // ...
  4. }
  5. get prop() {
  6. return 'getter';
  7. }
  8. set prop(value) {
  9. console.log('setter: '+value);
  10. }
  11. }
  12. let inst = new MyClass();
  13. inst.prop = 123;
  14. // setter: 123
  15. inst.prop
  16. // 'getter'

上面代码中,prop属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。

存值函数和取值函数是设置在属性的 Descriptor 对象上的。

  1. class CustomHTMLElement {
  2. constructor(element) {
  3. this.element = element;
  4. }
  5. get html() {
  6. return this.element.innerHTML;
  7. }
  8. set html(value) {
  9. this.element.innerHTML = value;
  10. }
  11. }
  12. var descriptor = Object.getOwnPropertyDescriptor(
  13. CustomHTMLElement.prototype, "html"
  14. );
  15. "get" in descriptor // true
  16. "set" in descriptor // true

上面代码中,存值函数和取值函数是定义在html属性的描述对象上面,这与 ES5 完全一致。

Class 的 Generator 方法

如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数。

  1. class Foo {
  2. constructor(...args) {
  3. this.args = args;
  4. }
  5. * [Symbol.iterator]() {
  6. for (let arg of this.args) {
  7. yield arg;
  8. }
  9. }
  10. }
  11. for (let x of new Foo('hello', 'world')) {
  12. console.log(x);
  13. }
  14. // hello
  15. // world

上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个 Generator 函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for...of循环会自动调用这个遍历器。

Class 的静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

  1. class Foo {
  2. static classMethod() {
  3. return 'hello';
  4. }
  5. }
  6. Foo.classMethod() // 'hello'
  7. var foo = new Foo();
  8. foo.classMethod()
  9. // TypeError: foo.classMethod is not a function

上面代码中,Foo类的classMethod方法前有static关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。

注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。

  1. class Foo {
  2. static bar () {
  3. this.baz();
  4. }
  5. static baz () {
  6. console.log('hello');
  7. }
  8. baz () {
  9. console.log('world');
  10. }
  11. }
  12. Foo.bar() // hello

上面代码中,静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。

父类的静态方法,可以被子类继承。

  1. class Foo {
  2. static classMethod() {
  3. return 'hello';
  4. }
  5. }
  6. class Bar extends Foo {
  7. }
  8. Bar.classMethod() // 'hello'

上面代码中,父类Foo有一个静态方法,子类Bar可以调用这个方法。

静态方法也是可以从super对象上调用的。

  1. class Foo {
  2. static classMethod() {
  3. return 'hello';
  4. }
  5. }
  6. class Bar extends Foo {
  7. static classMethod() {
  8. return super.classMethod() + ', too';
  9. }
  10. }
  11. Bar.classMethod() // "hello, too"

Class 的静态属性和实例属性

静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。

  1. class Foo {
  2. }
  3. Foo.prop = 1;
  4. Foo.prop // 1

上面的写法为Foo类定义了一个静态属性prop

目前,只有这种写法可行,因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性。

  1. // 以下两种写法都无效
  2. class Foo {
  3. // 写法一
  4. prop: 2
  5. // 写法二
  6. static prop: 2
  7. }
  8. Foo.prop // undefined

目前有一个静态属性的提案,对实例属性和静态属性都规定了新的写法。

(1)类的实例属性

类的实例属性可以用等式,写入类的定义之中。

  1. class MyClass {
  2. myProp = 42;
  3. constructor() {
  4. console.log(this.myProp); // 42
  5. }
  6. }

上面代码中,myProp就是MyClass的实例属性。在MyClass的实例上,可以读取这个属性。

以前,我们定义实例属性,只能写在类的constructor方法里面。

  1. class ReactCounter extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. count: 0
  6. };
  7. }
  8. }

上面代码中,构造方法constructor里面,定义了this.state属性。

有了新的写法以后,可以不在constructor方法里面定义。

  1. class ReactCounter extends React.Component {
  2. state = {
  3. count: 0
  4. };
  5. }

这种写法比以前更清晰。

为了可读性的目的,对于那些在constructor里面已经定义的实例属性,新写法允许直接列出。

  1. class ReactCounter extends React.Component {
  2. state;
  3. constructor(props) {
  4. super(props);
  5. this.state = {
  6. count: 0
  7. };
  8. }
  9. }

(2)类的静态属性

类的静态属性只要在上面的实例属性写法前面,加上static关键字就可以了。

  1. class MyClass {
  2. static myStaticProp = 42;
  3. constructor() {
  4. console.log(MyClass.myStaticProp); // 42
  5. }
  6. }

同样的,这个新写法大大方便了静态属性的表达。

  1. // 老写法
  2. class Foo {
  3. // ...
  4. }
  5. Foo.prop = 1;
  6. // 新写法
  7. class Foo {
  8. static prop = 1;
  9. }

上面代码中,老写法的静态属性定义在类的外部。整个类生成以后,再生成静态属性。这样让人很容易忽略这个静态属性,也不符合相关代码应该放在一起的代码组织原则。另外,新写法是显式声明(declarative),而不是赋值处理,语义更好。

new.target 属性

new是从构造函数生成实例对象的命令。ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。

  1. function Person(name) {
  2. if (new.target !== undefined) {
  3. this.name = name;
  4. } else {
  5. throw new Error('必须使用 new 命令生成实例');
  6. }
  7. }
  8. // 另一种写法
  9. function Person(name) {
  10. if (new.target === Person) {
  11. this.name = name;
  12. } else {
  13. throw new Error('必须使用 new 命令生成实例');
  14. }
  15. }
  16. var person = new Person('张三'); // 正确
  17. var notAPerson = Person.call(person, '张三'); // 报错

上面代码确保构造函数只能通过new命令调用。

Class 内部调用new.target,返回当前 Class。

  1. class Rectangle {
  2. constructor(length, width) {
  3. console.log(new.target === Rectangle);
  4. this.length = length;
  5. this.width = width;
  6. }
  7. }
  8. var obj = new Rectangle(3, 4); // 输出 true

需要注意的是,子类继承父类时,new.target会返回子类。

  1. class Rectangle {
  2. constructor(length, width) {
  3. console.log(new.target === Rectangle);
  4. // ...
  5. }
  6. }
  7. class Square extends Rectangle {
  8. constructor(length) {
  9. super(length, length);
  10. }
  11. }
  12. var obj = new Square(3); // 输出 false

上面代码中,new.target会返回子类。

利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

  1. class Shape {
  2. constructor() {
  3. if (new.target === Shape) {
  4. throw new Error('本类不能实例化');
  5. }
  6. }
  7. }
  8. class Rectangle extends Shape {
  9. constructor(length, width) {
  10. super();
  11. // ...
  12. }
  13. }
  14. var x = new Shape(); // 报错
  15. var y = new Rectangle(3, 4); // 正确

上面代码中,Shape类不能被实例化,只能用于继承。

注意,在函数外部,使用new.target会报错。