ES6 類的基本概念
ES6 引入了基于類的面向對象編程語法,通過 class
關鍵字定義類。類可以包含構造函數、方法和屬性。
class Person {constructor(name) {this.name = name;}greet() {console.log(`Hello, ${this.name}!`);}
}const person = new Person('Alice');
person.greet(); // 輸出: Hello, Alice!
類的繼承
使用 extends
關鍵字實現繼承,子類可以繼承父類的屬性和方法。
class Student extends Person {constructor(name, grade) {super(name); // 調用父類構造函數this.grade = grade;}study() {console.log(`${this.name} is studying in grade ${this.grade}.`);}
}const student = new Student('Bob', 5);
student.greet(); // 輸出: Hello, Bob!
student.study(); // 輸出: Bob is studying in grade 5.
靜態方法與屬性
靜態方法和屬性屬于類本身,而非實例。通過 static
關鍵字定義。
class MathHelper {static PI = 3.14159;static calculateArea(radius) {return this.PI * radius * radius;}
}console.log(MathHelper.calculateArea(5)); // 輸出: 78.53975
類的訪問器
通過 get
和 set
定義訪問器屬性,控制屬性的讀取和賦值行為。
class Temperature {constructor(celsius) {this._celsius = celsius;}get fahrenheit() {return this._celsius * 9 / 5 + 32;}set fahrenheit(value) {this._celsius = (value - 32) * 5 / 9;}
}const temp = new Temperature(25);
console.log(temp.fahrenheit); // 輸出: 77
temp.fahrenheit = 86;
console.log(temp._celsius); // 輸出: 30
類的私有字段
ES2022 引入了私有字段(Private Fields),通過在字段名前加 #
實現私有化。
class Counter {#count = 0;increment() {this.#count++;}getCount() {return this.#count;}
}const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 輸出: 1
// console.log(counter.#count); // 報錯: Private field '#count' must be declared in an enclosing class
類的檢查與擴展
使用 instanceof
檢查對象是否屬于某個類,通過 Object.getPrototypeOf
獲取原型鏈。
console.log(student instanceof Student); // true
console.log(student instanceof Person); // true
console.log(Object.getPrototypeOf(student) === Student.prototype); // true
以上內容涵蓋了 ES6 類的核心特性,包括定義、繼承、靜態成員、訪問器、私有字段以及類型檢查。