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 开了 50 英里。总里程:50"
console.log(myCar.getDetails()); // "Toyota Camry, 里程: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); // 输出: 存入 50。新余额: 150
account.withdraw(30); // 输出: 取出 30。新余额: 120
console.log(account.getBalance()); // 输出: 120
// 尝试访问私有方法或属性会引发错误
account.#balance; // SyntaxError
account.#validateAmount(50); // SyntaxError
GO TO FULL VERSION