引言
JavaScript(JS)作为一种广泛应用于网页开发的脚本语言,其面向对象编程(OOP)是其核心特性之一。掌握JS面向对象编程,对于编写高效、可维护的代码至关重要。本文将通过一系列实战练习题,帮助你深入理解JS面向对象编程,并提升你的实战能力。
一、面向对象基础
1.1 定义类与创建对象
题目描述:请定义一个Person类,包含属性name和age,以及方法sayHello。
解题思路:
- 使用
class关键字定义类。 - 在类中定义构造函数,初始化属性。
- 定义方法。
代码示例:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
1.2 继承
题目描述:请定义一个Student类,继承自Person类,并添加属性grade。
解题思路:
- 使用
extends关键字实现继承。 - 在
Student类中,调用super关键字来调用父类的构造函数。
代码示例:
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
}
二、实战练习题
2.1 创建一个BankAccount类,包含属性name、balance和transactions,以及方法deposit和withdraw。
解题思路:
- 定义
BankAccount类,初始化属性。 deposit方法:增加余额。withdraw方法:减少余额,并检查余额是否足够。
代码示例:
class BankAccount {
constructor(name, balance = 0) {
this.name = name;
this.balance = balance;
this.transactions = [];
}
deposit(amount) {
this.balance += amount;
this.transactions.push(`Deposited: ${amount}`);
}
withdraw(amount) {
if (this.balance >= amount) {
this.balance -= amount;
this.transactions.push(`Withdrawn: ${amount}`);
} else {
console.log('Insufficient balance');
}
}
getTransactions() {
return this.transactions;
}
}
2.2 请实现一个Queue类,包含方法enqueue、dequeue和peek。
解题思路:
- 使用数组来实现队列。
enqueue方法:将元素添加到队列末尾。dequeue方法:移除队列首部元素。peek方法:查看队列首部元素,但不移除。
代码示例:
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
return this.items.shift();
}
peek() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
三、总结
通过以上实战练习题,相信你已经对JS面向对象编程有了更深入的理解。面向对象编程的核心思想是将数据和操作数据的方法封装在一起,这有助于提高代码的可维护性和可扩展性。在今后的项目中,灵活运用面向对象编程的思想,将使你的代码更加出色。
