在JavaScript中,面向对象编程(OOP)是一种流行的编程范式,它允许开发者创建可重用和可维护的代码。通过使用类和对象,我们可以将数据和行为封装在一起,从而实现更加模块化的代码结构。以下是一些实用的JavaScript面向对象编程实例,帮助你轻松掌握类和对象创建技巧。
实例1:创建一个简单的类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person('Alice', 30);
person1.greet(); // 输出:Hello, my name is Alice and I am 30 years old.
在这个例子中,我们创建了一个名为Person的类,它有两个属性:name和age,以及一个方法greet。通过使用new关键字,我们可以创建一个Person类的实例,并调用其方法。
实例2:继承
class Employee extends Person {
constructor(name, age, job) {
super(name, age);
this.job = job;
}
introduce() {
console.log(`I am ${this.name}, ${this.age} years old, and I work as a ${this.job}.`);
}
}
const employee1 = new Employee('Bob', 25, 'developer');
employee1.introduce(); // 输出:I am Bob, 25 years old, and I work as a developer.
在这个例子中,我们创建了一个名为Employee的类,它继承自Person类。Employee类添加了一个新的属性job和一个方法introduce。通过使用super关键字,我们可以调用父类Person的构造函数。
实例3:静态方法
class MathUtils {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(MathUtils.add(5, 3)); // 输出:8
console.log(MathUtils.subtract(5, 3)); // 输出:2
在这个例子中,我们创建了一个名为MathUtils的类,其中包含两个静态方法:add和subtract。静态方法可以直接通过类名调用,而不需要创建类的实例。
实例4:属性封装
class BankAccount {
constructor(balance) {
this._balance = balance;
}
getBalance() {
return this._balance;
}
deposit(amount) {
this._balance += amount;
}
withdraw(amount) {
if (amount <= this._balance) {
this._balance -= amount;
} else {
console.log('Insufficient funds');
}
}
}
const account = new BankAccount(1000);
console.log(account.getBalance()); // 输出:1000
account.deposit(500);
console.log(account.getBalance()); // 输出:1500
account.withdraw(2000); // 输出:Insufficient funds
console.log(account.getBalance()); // 输出:1500
在这个例子中,我们创建了一个名为BankAccount的类,其中包含一个私有属性_balance。我们使用getBalance、deposit和withdraw方法来访问和修改这个属性。这样,我们可以确保_balance的值不会被外部直接修改。
实例5:属性装饰器
class Person {
@readonly
name;
constructor(name) {
this.name = name;
}
}
function readonly(target, key, descriptor) {
descriptor.writable = false;
return descriptor;
}
const person = new Person('Alice');
console.log(person.name); // 输出:Alice
person.name = 'Bob'; // 抛出错误:Cannot assign to read only property 'name' of object '#<Person>'
在这个例子中,我们使用了一个属性装饰器readonly来确保name属性不可修改。这样,一旦设置了name的值,它就不能再被更改。
实例6:方法装饰器
class Person {
@logMethod
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
function logMethod(target, key, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function() {
console.log(`Method ${key} called`);
return originalMethod.apply(this, arguments);
};
return descriptor;
}
const person = new Person('Alice');
person.greet(); // 输出:Method greet called
// 输出:Hello, my name is Alice
在这个例子中,我们使用了一个方法装饰器logMethod来记录方法的调用。这样,每次调用greet方法时,我们都会先输出一条日志信息。
通过这些实用的JavaScript面向对象编程实例,相信你已经掌握了类和对象创建技巧。在实际开发中,灵活运用这些技巧,可以让你编写出更加高效、可维护的代码。
