Class

344 阅读1分钟

Class

@TODO

class Foo {
    constructor (a, b) {
        this.x = a;
        this.y = b;
    }
    gimmeXY () {
        return this.x * this.y;
    }
}
  • 只能通过new Foo()来实例化,Foo.call(obj)是不允许的
  • Foo是不会提升的,继承或者实例化之前要先声明

构造器

对于类和子类来说,构造器并不是必须的,如果省略的话会有默认构造器。

默认子类构造器自动调用父类的构造器并传递所有参数。

子类构造器中调用super(..)之后才能访问this

class Foo {
    constructor () {
        this.a = 1;
    }
}

class Bar extends Foo {
    constructor () {
        this.b = 2; // 不允许在super()之前
        super(); // 要改正的话可以交换这两条语句
    }
}

扩展原生类

class myArray extends Array {
    first () {}
    last () {}
}

元属性

new.target是undefined的话,这个函数不是通过new调用的

static

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

class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

Symbol.species Getter构造器

class MyCoolArray extends Array {
    static get [Symbol.species]() { return Array }
}
var a = new MyCoolArray(1, 2, 3);
b = a.map((v) => v * 2) 
b instanceof MyCoolArray; // false
b instanceof Array; // true