Skip to content

Class

对于面向对象编程而言,更关注类的声明、属性、方法、静态方法、继承、多态、私有属性。

声明类

使用关键字 Class 来声明,首字母大写

js
class Animal {
  constructor(type) {
    this.type = type;
  }
  walk() {
    console.log("行走中");
  }
}
let dog = new Animal("dog");
let monkey = new Animal("monkey");

INFO

类里面所有的函数不需要写 function

多个函数方法之间不需要逗号分隔

Setters & Getters

对于类中的属性,可以直接在 constructor 中通过 this 直接定义,还可以在类的顶层定义

js
class Animal {
  constructor(type, age) {
    this.type = type;
    this._age = age;
  }
  get age() {
    return this._age;
  }
  set age(val) {
    this._age = val;
  }
}

毋庸赘述,大家都能看出来含义。再来看下如下的应用场景:

js
class CustomHTMLElement {
  constructor(element) {
    this.element = element;
  }
  get html() {
    return this.element.innerHTML;
  }
  set html(value) {
    this.element.innerHTML = value;
  }
}

可是,有时候我们真的需要设置一个私有属性(闭包),然后通过一定的规则来限制对它的修改,利用 set/get 就可以轻松实现。

js
let #age = 1
class Animal {
    constructor(type) {
        this.type = type
    }
    get age() {
        return #age
    }
    set age(val) {
        if (val > 0 && val < 10) {
            #age = val
        }
    }
}

静态方法

不用实例化直接使用

js
class Animal {
  constructor(type) {
    this.type = type;
  }
  walk() {
    console.log(`I am walking`);
  }
  static eat() {
    console.log(`I am eating`);
  }
}
Animal.eat();

继承

ES6 通过关键字 extends,super 是继承父类,可以调用父类的方法

js
class Animal {
  constructor(type) {
    this.type = type;
  }
  walk() {
    console.log(`I am walking`);
  }
  static eat() {
    console.log(`I am eating`);
  }
}

class Dog extends Animal {
  constructor() {
    super("dog");
  }
  run() {
    console.log("I can run");
    super.walk();
  }
}

推荐阅读