class

144 阅读9分钟

什么是Class

对一类具有共同特征的事物的抽象(构造函数语法糖)

在以前我们定义类是使用的函数也就是构造函数来实现的

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 Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

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

使用 class 来定义类 其实就跟使用构造函数定义类一样 就是两种写法 class可以看做是构造函数的语法糖,类的类型就是function,类本身就指向构造函数

class Point {
  // ...
}

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

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

class Point {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于

Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

constructor

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

class Point {
}

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

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

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

class Foo {
  constructor() {
    return Object.create(null);
  }
}

new Foo() instanceof Foo
// false

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

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

class Foo {
  constructor() {
    return Object.create(null);
  }
}

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

实例属性的新写法

ES2022 为类的实例属性又规定了一种新写法。实例属性现在除了可以定义在constructor()方法里面的this上面,也可以定义在类内部的最顶层。

原来的写法是实例属性_count是定义在constructor里面的this上面

class IncreasingCounter {
  constructor() {
    this._count = 0;
  }
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}

现在这个属性可以定义在类的最顶层,其他保持不变

class IncreasingCounter {
  _count = 0;
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}

写在最顶成的属性是实例对象自身的属性,而不是定义在实例对象的原型上面

Class 表达式

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

const myPerson = class person {
  name = "张三";
  getName() {
      console.log(this) // 这里的this指向的是 person 类
      return this.name
  }
};
let p = new myPerson()
console.log(p.getName()) // 张三

静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上

static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class person{
    static getName(){
        return person.name
    }
}
console.log(person.getName()) // person
let p = new person()
console.log(p.getName()) // p.getName is not a function

在上面的类中 getName()方法前面有 static 关键字 ,所以不会被实例所继承,所以

p.getName()会报错

静态属性

在属性前面加上 static 关键字,这个属性就是静态属性,同样不会被实例所继承。

class person{
    static age = 18 // 不可以被继承
  	name = '张三' // 可以被继承
}
let p = new person()
console.log(p.age) // undefined
console.log(p.name) // 张三

私有属性和私有方法

ES2022正式为class添加了私有属性,方法是在属性名之前使用#表示。

class person{
    #age = 18 // 私有属性
    name = '张三' // 公有属性
  	#getName(){   // 私有方法
        return person.name
    }
}
let p = new person()
console.log(p.age) // undefined
console.log(p.name) // 张三

另外,不管在类的内部或外部,读取一个不存在的私有属性,也都会报错。这跟公开属性的行为完全不同,如果读取一个不存在的公开属性,不会报错,只会返回undefined

类的注意点

不存在提升

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

new Foo(); // ReferenceError
class Foo {}

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

{
  let Foo = class {};
  class Bar extends Foo {
  }
}

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

name属性

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

name属性。

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

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

Class的继承

Class 可以通过extends关键字实现继承,让子类继承父类的属性和方法。extends 的写法比 ES5 的原型链继承,要清晰和方便很多。

class parent {
    name = '张三'
}
class son extends parent{
    age = 18
}

let s = new son()
console.log(s) // {name:'张三',age:18}

上面的代码中 类 parent 中有一个name属性,类 son 继承了父类 parent的属性和方法,

所以类 son也有name属性

class parent {
    m = 4
    constructor(x,y){
        console.log(this) // this指向类本身 {m:4}
        this.x = x
        this.y = y
    }
    toString(){
        console.log(this) // this指向实例 
        return this.x + this.y
    }
}
class son extends parent {
    constructor(x, y, color) {
        super(x, y); // 子类必须先调用super() 得到父类的属性和方法 才有自己的this对象 
        console.log(this) // this指向父级的实例
        this.color = color;
    }
    toString() {
      	return this.color
    }
}

let s = new son(1,2,'red');
console.log(s.toString());

super在这里表示父类的构造函数,用来新建一个父类的实例对象。

ES6 规定,子类必须在constructor()方法中调用super(),否则就会报错。这是因为子类自己的

this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,添加子类自己的实例属性和方法。如果不调用super()方法,子类就得不到自己的this对象。

为什么子类的构造函数,一定要调用super()

原因就在于 ES6 的继承机制,与 ES5 完全不同。ES5 的继承机制,是先创造一个独立的子类的实例对象,然后再将父类的方法添加到这个对象上面,即“实例在前,继承在后”。ES6 的继承机制,则是先将父类的属性和方法,加到一个空的对象上面,然后再将该对象作为子类的实例,即“继承在前,实例在后”。这就是为什么 ES6 的继承必须先调用super()方法,因为这一步会生成一个继承父类的this对象,没有这一步就无法继承父类。

注意,这意味着新建子类实例时,父类的构造函数必定会先运行一次。

class Foo {
  constructor() {
    console.log(1);
  }
}

class Bar extends Foo {
  constructor() {
    super();  // 执行父类的构造函数
    console.log(2);
  }
}

const bar = new Bar();
// 1
// 2

子类Bar创建实例的时候会打印 1 和2 这就是因为子类构造函数调用super的时候会执行一遍父类的构造函数

还有就是在子类构造函数中,只有调用super()之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,必须先完成父类的继承,只有super()方法才能让子类实例继承父类。

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class ColorPoint extends Point {
  constructor(x, y, color) {
    this.color = color; // ReferenceError
    super(x, y);
    this.color = color; // 正确
  }
}

如果子类继承的时候没有定义constructor,如下

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class ColorPoint extends Point {
  
}
const c = new ColorPoint(1,2)
console.log(c) // {x:1,y:2}

这样也不会报错,这是因为如果子类没有定义constructor()方法,这个方法会默认添加,并且里面会调用super()。也就是说,不管有没有显式定义,任何一个子类都有constructor()方法。

class ColorPoint extends Point {
}

// 等同于
class ColorPoint extends Point {
  constructor(...args) {
    super(...args);
  }
}

有了子类的定义,就可以生成子类的实例了。

let c = new ColorPoint(25, 8, 'green');

c instanceof ColorPoint // true
c instanceof Point // true

上面示例中,实例对象cp同时是ColorPointPoint两个类的实例,这与 ES5 的行为完全一致。

私有属性和私有方法的继承

父类所有的属性和方法,都会被子类继承,除了私有的属性和方法。

子类无法继承父类的私有属性,或者说,私有属性只能在定义它的 class 里面使用。

class Foo {
  #p = 1;
  #m() {
    console.log('hello');
  }
}

class Bar extends Foo {
  constructor() {
    super();
    console.log(this.#p); // 报错
    this.#m(); // 报错
  }
}

上面示例中,子类 Bar 调用父类 Foo 的私有属性或私有方法,都会报错。

如果父类定义了私有属性的读写方法,子类就可以通过这些方法,读写私有属性。

class Foo {
  #p = 1;
  getP() {
    return this.#p;
  }
}

class Bar extends Foo {
  constructor() {
    super();
    console.log(this.getP()); // 1
  }
}

上面示例中,getP()是父类用来读取私有属性的方法,通过该方法,子类就可以读到父类的私有属性。

静态属性和静态方法的继承

父类的静态属性和静态方法,也会被子类继承。

class A {
  static hello() {
    console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world

上面代码中,hello()A类的静态方法,B继承A,也继承了A的静态方法。

注意,静态属性是通过软拷贝实现继承的。

class A { static foo = 100; }
class B extends A {
  constructor() {
    super();
    B.foo--;
  }
}

const b = new B();
B.foo // 99
A.foo // 100

上面示例中,foo是 A 类的静态属性,B 类继承了 A 类,因此也继承了这个属性。但是,在 B 类内部操作B.foo这个静态属性,影响不到A.foo,原因就是 B 类继承静态属性时,会采用浅拷贝,拷贝父类静态属性的值,因此A.fooB.foo是两个彼此独立的属性。

但是,由于这种拷贝是浅拷贝,如果父类的静态属性的值是一个对象,那么子类的静态属性也会指向这个对象,因为浅拷贝只会拷贝对象的内存地址。

class A {
  static foo = { n: 100 };
}

class B extends A {
  constructor() {
    super();
    B.foo.n--;
  }
}

const b = new B();
B.foo.n // 99
A.foo.n // 99

上面示例中,A.foo的值是一个对象,浅拷贝导致B.fooA.foo指向同一个对象。所以,子类B修改这个对象的属性值,会影响到父类A。

Object.getPrototypeOf()

Object.getPrototypeOf()方法可以用来从子类上获取父类。

class Point { /*...*/ }

class ColorPoint extends Point { /*...*/ }

Object.getPrototypeOf(ColorPoint) === Point
// true

因此,可以使用这个方法判断,一个类是否继承了另一个类。