JavaScript ES6 class 类

  1. constructor内外都可以定义属性,前面加static为静态属性
  2. 类里面,方法(){}为成员方法,加static为静态方法constructorthis.方法()为实例方法
  3. 继承父类方法使用extends,子类没有constructor时会默认调用父类的constructor
  4. 子类constructor内使用this之前必须调用super()方法把父类的this继承下来
  5. 成员属性、方法、静态属性、方法也会继承下来。子类使用父类方法可以super.方法名,也可以this.方法
  6. 子类用super.父类属性,也可以使用this来获取
  7. 静态方法不能访问成员属性,成员方法不能访问静态属性
1class Person {
2  name // 成员属性
3  static age = 2 // 静态属性
4  constructor(name, age) {
5    this.name = name
6    this.age = age // 这里 this.age 指向实例的 age
7  }
8
9  fn() {
10    // 成员方法(原型上)
11    console.log(this.age + Person.age)
12  }
13
14  static fn1() {
15    // 静态方法 只能使用 Person.fn1()来调用
16    console.log(this.age === Person.age) // true
17  }
18}
19
20class Son extends Person {
21  constructor(name, age, sex) {
22    super(name, age) // this之前调用super
23    super.fn() // 调用父类方法
24    this.sex = sex
25  }
26
27  fn() {
28    // 重写父类方法
29  }
30
31  static ff() {
32    super.fn1() // 调用父类静态方法
33  }
34}
35
36// 不可继承常规对象。
37const Father = {
38  // ...
39}
40class Child extends Father {
41  // ...
42}
43// Uncaught TypeError: Class extends value #<Object> is not a constructor or null
44
45// 解决方案
46Object.setPrototypeOf(Child.prototype, Father)