class类基础知识

本文介绍了JavaScript中的类定义,包括构造函数、方法以及使用`extends`进行继承。详细讲解了`super`关键字的用法,静态属性和方法的声明及调用,以及如何通过`set`和`get`控制受保护的属性。此外,还提到了ES6新增的私有属性`#`的特性,强调了其只能在类的内部访问的限制。
摘要由CSDN通过智能技术生成

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 获取age
  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(); // 调用父类的 stop
    this.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 = Article
    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; // _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 方法修改调用私有的属性方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值