JS如何实现面向对象
基于原型的面向对象实现
JavaScript 采用基于原型的面向对象模式,通过构造函数和原型链实现继承。构造函数用于定义对象的属性和方法,原型用于共享方法和属性。
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
const person1 = new Person('Alice', 25);
console.log(person1.greet());
使用 class 语法糖
ES6 引入了 class 语法,使面向对象编程更接近传统语言风格。class 本质仍是基于原型的语法糖。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
const person2 = new Person('Bob', 30);
console.log(person2.greet());
实现继承
JavaScript 通过原型链实现继承。子类可以继承父类的属性和方法,并可以添加或覆盖它们。
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age);
this.jobTitle = jobTitle;
}
greet() {
return `${super.greet()} and I work as ${this.jobTitle}`;
}
}
const employee = new Employee('Charlie', 35, 'Developer');
console.log(employee.greet());
封装与访问控制
虽然 JavaScript 没有内置的访问修饰符,但可以通过闭包或 Symbol 实现类似效果。
class BankAccount {
#balance = 0; // 私有字段
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance());
多态实现
JavaScript 的动态类型系统天然支持多态,不同对象可以对相同方法名做出不同响应。
class Animal {
speak() {
return 'Some sound';
}
}
class Dog extends Animal {
speak() {
return 'Woof!';
}
}
class Cat extends Animal {
speak() {
return 'Meow!';
}
}
const animals = [new Animal(), new Dog(), new Cat()];
animals.forEach(animal => console.log(animal.speak()));
对象组合优于继承
在复杂场景下,使用对象组合比深度继承更灵活。通过将功能分解为独立对象并组合使用。
const canSwim = {
swim() {
return 'Swimming';
}
};
const canFly = {
fly() {
return 'Flying';
}
};
class Duck {
constructor() {
Object.assign(this, canSwim, canFly);
}
}
const duck = new Duck();
console.log(duck.swim(), duck.fly());






