6.1 類別的構造函數
類別的構造函數和方法是 JavaScript 中面向對象編程的基本元素。 它們允許創建和初始化對象,並定義其行為。接下來我們看看構造函數和類別方法是如何工作的,並如何使用它們。
什麼是構造函數?
構造函數是一個類別的特殊方法,在創建類別的新實例時調用。 它用於初始化對象,設置其屬性的值並執行其他初始任務。
構造函數的定義
構造函數是使用關鍵字 constructor
定義的。在構造函數內部可以使用
關鍵字 this
訪問對象的屬性和方法。
語法:
class ClassName {
constructor(參數) {
// 初始化對象
}
}
範例:
在類別 Person
中,方法 constructor
接受兩個參數:name
和 age
。
這些參數用於初始化所創建對象的屬性 name
和 age
。
JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
console.log(person1.name); // 顯示: Alice
console.log(person2.age); // 顯示: 25
默認構造函數
如果構造函數未明確定義,JavaScript 會自動創建一個空的默認構造函數。
範例:
JavaScript
class Animal {}
const animal = new Animal();
console.log(animal); // 顯示類別 Animal 的內容 {}
4.2 類別的方法
類別的方法在類別體中定義,提供由該類別創建的對象的功能。 方法自動添加到類別的原型中,這使所有類別的實例都可以繼承並使用它們。
語法:
class ClassName {
constructor(參數) {
// 初始化對象
}
方法1() {
// 方法體
}
方法2() {
// 方法體
}
}
範例:
JavaScript
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
this.mileage = 0;
}
drive(distance) {
this.mileage += distance;
console.log(`${this.brand} ${this.model} drove ${distance} miles. Total mileage: ${this.mileage}`);
}
getDetails() {
return `${this.brand} ${this.model}, Mileage: ${this.mileage}`;
}
}
const myCar = new Car('Toyota', 'Camry');
myCar.drive(50); // "Toyota Camry drove 50 miles. Total mileage: 50"
console.log(myCar.getDetails()); // "Toyota Camry, Mileage: 50"
說明:
- 在類別
Car
中定義了兩個方法:drive()
和getDetails()
- 方法
drive()
增加汽車的里程並輸出已行駛的距離信息 - 方法
getDetails()
返回有關汽車的信息字符串
6.3 私有方法
隨著新 ECMAScript 規範的引入,現在可以創建私有方法和屬性,這些方法和屬性在類別外部不可訪問。為此,符號 # 用作名稱的一部分。
私有方法和屬性的範例:
JavaScript
class BankAccount {
#balance = 0;
constructor(initialBalance) {
this.#balance = initialBalance;
}
#validateAmount(amount) {
if (amount <= 0) {
throw new Error('Amount must be positive.');
}
}
deposit(amount) {
this.#validateAmount(amount);
this.#balance += amount;
console.log(`Deposited ${amount}. New balance: ${this.#balance}`);
}
withdraw(amount) {
this.#validateAmount(amount);
if (amount > this.#balance) {
throw new Error('Insufficient funds.');
}
this.#balance -= amount;
console.log(`Withdrew ${amount}. New balance: ${this.#balance}`);
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(100);
account.deposit(50); // 顯示: Deposited 50. New balance: 150
account.withdraw(30); // 顯示: Withdrew 30. New balance: 120
console.log(account.getBalance()); // 顯示: 120
// 嘗試訪問私有方法或屬性將引發錯誤
account.#balance; // SyntaxError
account.#validateAmount(50); // SyntaxError
GO TO FULL VERSION