静态
静态方法
把一个方法赋值给类的函数本身,而不是赋给它的 "prototype"。这样的方法被称为静态的(static)。
通常,静态方法用于实现属于该类但不属于该类任何特定对象的函数。
class User { }User.staticMethod = function() {alert(this === User);};User.staticMethod(); // true
静态属性
class Article {static publisher = "Levi Ding";}alert( Article.publisher ); // Levi Ding
继承静态属性和方法
实现原理:
extends 让 Rabbit 的 [[Prototype]] 指向了 Animal。
所以,Rabbit extends Animal 创建了两个 [[Prototype]] 引用:
Rabbit** 构造函数的原型指向Animal函数。**Rabbit.prototype** 原型指向Animal.prototype。**

class Animal {}class Rabbit extends Animal {}// 对于静态的alert(Rabbit.__proto__ === Animal); // true// 对于常规方法alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
私有的和受保护
在面向对象的编程中,属性和方法分为两组:
- 内部接口 —— 可以通过该类的其他方法访问,但不能从外部访问的方法和属性。
- 外部接口 —— 也可以从类的外部访问的方法和属性。
在 JavaScript 中,有两种类型的对象字段(属性和方法):
- 公共的:可从任何地方访问。它们构成了外部接口。到目前为止,只使用了公共的属性和方法。
- 私有的:只能从类的内部访问。这些用于内部接口。
受保护属性
受保护的属性通常以下划线 _ 作为前缀。主要通过getter和setter访问器属性实现
但这种实现,**仍能被继承**到;
class CoffeeMachine {_waterAmount = 0;set waterAmount(value) {if (value < 0) throw new Error("Negative water");this._waterAmount = value;}get waterAmount() {return this._waterAmount;}constructor(power) {this._power = power;}}// 创建咖啡机let coffeeMachine = new CoffeeMachine(100);// 加水coffeeMachine.waterAmount = -10; // Error: Negative water
私有的**
- 私有属性和方法应该以 **
#** 开头。 - 它们只在类的内部可被访问。无法从外部或从继承的类中访问它。
- 私有字段不能通过 this[name] 访问
同时, 私有字段 与 公共字段 不会发生冲突。可以同时拥有私有的 #waterAmount 和公共的 waterAmount 字段。
class CoffeeMachine {#waterLimit = 200;#checkWater(value) {if (value < 0) throw new Error("Negative water");if (value > this.#waterLimit) throw new Error("Too much water");}sayHi() {let fieldName = "name";alert(`Hello, ${this[fieldName]}`); // 报错}}let coffeeMachine = new CoffeeMachine();// 不能从类的外部访问类的私有属性和方法coffeeMachine.#checkWater(); // ErrorcoffeeMachine.#waterLimit = 1000; // Error
