> 文章列表 > class类基础知识

class类基础知识

class类基础知识

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'//生成实例的时候this.age 获取ageconstructor(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(); // 调用父类的 stopthis.hide(); // 然后 hide}
}let rabbit = new Rabbit("White Rabbit");rabbit.run(5); // White Rabbit runs with speed 5.
rabbit.stop(); // White Rabbit stands still. White Rabbit hides!
  • 在 extends 后允许任意表达式,而不仅仅是一个class
  • super可继承父级的属性方法,继承类的 constructor 必须调用 super(…),并且 (!) 一定要在使用 this 之前调用
  • 执行 super.method(…) 来调用一个父类方法。
  • 箭头函数没有 super

3.静态属性和静态方法

class Article {constructor(title, date) {this.title = title;this.date = date;}static createTodays() {// 记住 this = Articlereturn 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; // _waterAmount 将变为 0,而不是 -10 (设置waterAmount小于10的时候直接return0)
  • 约定俗成的以_ 开头的变量为受保护的变量,通过设置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); // Error
  • 私有属性和方法只能在类的内部调用,无法通过class 或实例的this调用
  • 可通过get/set 方法修改调用私有的属性方法