引言
JavaScript(JS)作为一门广泛应用于前端和后端的编程语言,其面向对象编程(OOP)是核心概念之一。面向对象编程可以帮助开发者更好地组织代码,提高代码的可维护性和可复用性。本文将通过一系列实战练习题,帮助读者深入理解JavaScript面向对象编程的核心技术。
一、基础概念
1.1 对象的定义
在JavaScript中,对象是一系列键值对的集合,每个键是一个字符串或符号,每个值可以是任何数据类型。
let person = {
name: 'Alice',
age: 25
};
1.2 创建对象
JavaScript提供了多种创建对象的方法:
- 字面量创建
let car = {
brand: 'Toyota',
model: 'Corolla'
};
- 构造函数创建
function Car(brand, model) {
this.brand = brand;
this.model = model;
}
let myCar = new Car('Honda', 'Civic');
- 对象创建工厂
function createCar(brand, model) {
return {
brand: brand,
model: model
};
}
let myCar = createCar('Honda', 'Civic');
- 类(ES6)
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
}
let myCar = new Car('Honda', 'Civic');
二、面向对象编程核心特性
2.1 封装
封装是将数据和操作数据的方法捆绑在一起,以隐藏内部实现细节。
class Car {
constructor(brand, model) {
this._brand = brand;
this._model = model;
}
get brand() {
return this._brand;
}
set brand(value) {
this._brand = value;
}
get model() {
return this._model;
}
set model(value) {
this._model = value;
}
}
2.2 继承
继承允许一个类继承另一个类的属性和方法。
class SportsCar extends Car {
constructor(brand, model, topSpeed) {
super(brand, model);
this._topSpeed = topSpeed;
}
get topSpeed() {
return this._topSpeed;
}
set topSpeed(value) {
this._topSpeed = value;
}
}
2.3 多态
多态是指同一个方法在不同对象上有不同的表现。
class Animal {
makeSound() {
console.log('Some sound');
}
}
class Dog extends Animal {
makeSound() {
console.log('Woof!');
}
}
class Cat extends Animal {
makeSound() {
console.log('Meow!');
}
}
let dog = new Dog();
let cat = new Cat();
dog.makeSound(); // 输出:Woof!
cat.makeSound(); // 输出:Meow!
三、实战练习题
3.1 创建一个Person类,包含name、age属性和greet方法。
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.`);
}
}
let alice = new Person('Alice', 25);
alice.greet(); // 输出:Hello, my name is Alice and I am 25 years old.
3.2 创建一个BankAccount类,包含balance属性和deposit、withdraw方法。
class BankAccount {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
if (this.balance >= amount) {
this.balance -= amount;
} else {
console.log('Insufficient funds!');
}
}
}
let myAccount = new BankAccount(1000);
myAccount.deposit(500);
myAccount.withdraw(200);
console.log(myAccount.balance); // 输出:1300
3.3 创建一个Student类,继承自Person类,并添加grade属性和calculateAverage方法。
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
calculateAverage() {
return (this.grade.math + this.grade.science + this.grade.literature) / 3;
}
}
let john = new Student('John', 18, {
math: 90,
science: 85,
literature: 95
});
console.log(john.calculateAverage()); // 输出:90
通过以上实战练习题,相信读者已经对JavaScript面向对象编程有了更深入的理解。不断练习和实践,将有助于更好地掌握这一核心技术。
