
1.基本用法
class User {constructor(name) { this.name = name; }sayHi() { alert(this.name); }
}
let user=new User('张三');
console.log(user.sayHi())
2.extends 继承
class Animal {
age='16'constructor(name) {this.speed = 0;this.name = name;}run(speed) {this.speed = speed;alert(`${this.name} runs with speed ${this.speed}.`);}stop() {this.speed = 0;alert(`${this.name} stands still.`);}}class Rabbit extends Animal {hide() {alert(`${this.name} hides!`);}stop() {super.stop(); this.hide(); }
}let rabbit = new Rabbit("White Rabbit");rabbit.run(5);
rabbit.stop();
- 在 extends 后允许任意表达式,而不仅仅是一个class
- super可继承父级的属性或方法,继承类的 constructor 必须调用 super(…),并且 (!) 一定要在使用 this 之前调用
- 执行 super.method(…) 来调用一个父类方法。
- 箭头函数没有 super
3.静态属性和静态方法
class Article {constructor(title, date) {this.title = title;this.date = date;}static createTodays() {return new this("Today's digest", new Date());}
}let article = Article.createTodays();
- 静态属性和方法在生成实例中不能调用,但是可以直接调用这个class的方法
- 静态属性和方法也可以继承,在子类中调用父类的静态属性和方法(非实例中调用)
4.受保护的属性和方法
class CoffeeMachine {_waterAmount = 0;set waterAmount(value) {if (value < 0) {value = 0;}this._waterAmount = value;}get waterAmount() {return this._waterAmount;}setWaterAmount(value) {if (value < 0) value = 0;this._waterAmount = value;}getWaterAmount() {return this._waterAmount;}}
let coffeeMachine = new CoffeeMachine(100);
coffeeMachine.waterAmount = -10;
- 约定俗成的以_ 开头的变量为受保护的变量,通过设置set 和get 方法对该变量进行控制
- 受保护的字段是可以被继承的
5.私有的 “#waterLimit”(新增特性)
class CoffeeMachine {#waterAmount = 0;get waterAmount() {return this.#waterAmount;}set waterAmount(value) {if (value < 0) value = 0;this.#waterAmount = value;}
}let machine = new CoffeeMachine();machine.waterAmount = 100;
alert(machine.#waterAmount);
- 私有属性和方法只能在类的内部调用,无法通过class 或实例的this调用
- 可通过get/set 方法修改调用私有的属性方法