js面向对象的实现
JavaScript 面向对象实现方式
JavaScript 是一种基于原型的面向对象语言,与传统的基于类的语言(如 Java、C++)不同。以下是 JavaScript 中实现面向对象编程的几种主要方式:
构造函数模式
通过构造函数创建对象实例,使用 new 关键字调用构造函数:
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
const person1 = new Person('Alice', 25);
person1.sayHello();
原型模式
利用原型链实现属性和方法的共享,减少内存消耗:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Bob', 30);
person1.sayHello();
ES6 类语法
ES6 引入了 class 语法糖,使面向对象编程更接近传统语言:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person1 = new Person('Charlie', 35);
person1.sayHello();
工厂函数模式
不使用 new 关键字,通过函数返回对象:

function createPerson(name, age) {
return {
name,
age,
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
};
}
const person1 = createPerson('David', 40);
person1.sayHello();
组合使用构造函数和原型
结合构造函数初始化属性,原型定义方法:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person,
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
};
const person1 = new Person('Eve', 45);
person1.sayHello();
继承实现
JavaScript 通过原型链实现继承:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(`${this.name} barks.`);
};
const dog1 = new Dog('Rex');
dog1.speak();
ES6 类继承
使用 extends 关键字实现继承:

class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog1 = new Dog('Buddy');
dog1.speak();
对象创建方法
使用 Object.create() 创建对象:
const personProto = {
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
};
const person1 = Object.create(personProto);
person1.name = 'Frank';
person1.age = 50;
person1.sayHello();
私有成员实现
通过闭包或 ES2022 私有字段实现私有成员:
class Person {
#privateField;
constructor(name, secret) {
this.name = name;
this.#privateField = secret;
}
revealSecret() {
console.log(`My secret is ${this.#privateField}`);
}
}
const person1 = new Person('Grace', 'I love JavaScript');
person1.revealSecret();
Mixin 模式
实现多重继承的效果:
const canEat = {
eat() {
console.log(`${this.name} is eating.`);
}
};
const canWalk = {
walk() {
console.log(`${this.name} is walking.`);
}
};
function Person(name) {
this.name = name;
}
Object.assign(Person.prototype, canEat, canWalk);
const person1 = new Person('Henry');
person1.eat();
person1.walk();
每种实现方式都有其适用场景,开发者可以根据具体需求选择最合适的方法。ES6 类语法是目前最推荐的方式,它提供了更清晰的语法结构,同时底层仍然基于 JavaScript 的原型机制。






