js实现一个面向对象
面向对象编程基础
面向对象编程(OOP)的核心概念包括封装、继承和多态。JavaScript 通过构造函数、原型链和 ES6 的 class 语法支持 OOP。
使用构造函数实现
通过构造函数定义对象模板,结合 prototype 实现方法共享:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice', 25);
person1.greet(); // 输出: Hello, my name is Alice
关键点:

- 构造函数名通常首字母大写(约定)。
- 方法定义在
prototype上以避免重复创建函数实例。
使用 ES6 Class 语法
ES6 引入 class 关键字,语法更接近传统 OOP 语言:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // 输出: Rex barks.
特性:

extends实现继承。super()调用父类构造函数。
封装与私有字段
通过闭包或 # 前缀(ES2022)实现私有属性:
class Counter {
#count = 0; // 私有字段
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
多态的实现
通过方法重写实现多态行为:
class Shape {
draw() {
console.log('Drawing a shape');
}
}
class Circle extends Shape {
draw() {
console.log('Drawing a circle');
}
}
const shapes = [new Shape(), new Circle()];
shapes.forEach(shape => shape.draw());
// 输出:
// Drawing a shape
// Drawing a circle
静态方法与属性
使用 static 定义类级别的方法或属性:
class MathUtils {
static PI = 3.14159;
static square(x) {
return x * x;
}
}
console.log(MathUtils.square(3)); // 输出: 9






