JS如何实现面向对象
基于原型的面向对象实现
JavaScript 通过原型链实现面向对象编程。每个对象都有一个隐藏的 [[Prototype]] 属性(可通过 __proto__ 或 Object.getPrototypeOf() 访问),用于继承属性和方法。
构造函数模式:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, I'm ${this.name}`);
};
const person = new Person('Alice');
person.sayHello();
ES6 class 语法糖
ES6 引入的 class 语法更接近传统面向对象语言:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise`);
}
}
class Dog extends Animal {
speak() {
super.speak();
console.log(`${this.name} barks`);
}
}
const dog = new Dog('Rex');
dog.speak();
对象字面量与工厂模式
对于简单对象可以直接使用字面量:

const car = {
brand: 'Toyota',
drive() {
console.log(`Driving ${this.brand}`);
}
};
工厂函数模式:
function createUser(name) {
return {
name,
greet() {
console.log(`Hi, ${this.name}`);
}
};
}
私有成员实现
通过闭包或 ES2022 私有字段:

// 闭包方式
function Counter() {
let count = 0;
this.increment = function() {
return ++count;
};
}
// ES2022 私有字段
class Wallet {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
}
混入模式(Mixin)
实现多重继承的方式:
const canEat = {
eat() {
console.log('Eating');
}
};
const canWalk = {
walk() {
console.log('Walking');
}
};
function Person() {}
Object.assign(Person.prototype, canEat, canWalk);
静态方法与属性
使用 static 关键字定义:
class MathUtils {
static PI = 3.14159;
static square(x) {
return x * x;
}
}
console.log(MathUtils.square(5));
属性描述符
通过 Object.defineProperty 控制对象属性:
const obj = {};
Object.defineProperty(obj, 'readOnly', {
value: 42,
writable: false,
enumerable: true
});






