js面向对象的实现
JavaScript 面向对象实现方法
JavaScript 通过原型链和构造函数实现面向对象编程(OOP)。以下是几种常见的实现方式:
构造函数模式
通过函数定义对象类型,使用 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);
原型模式
共享方法和属性以减少内存占用:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person2 = new Person("Bob", 30);
类语法(ES6)
使用 class 关键字简化面向对象实现:

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person3 = new Person("Charlie", 35);
继承实现
通过原型链或 extends 实现继承:
// 原型链继承
function Student(name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
// ES6 类继承
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
}
封装与访问控制
通过闭包或 Symbol 实现私有属性:
class Person {
#privateField; // 私有字段(ES2022)
constructor(name) {
this.name = name;
this.#privateField = "secret";
}
}
注意事项
- 原型方法适用于所有实例共享的场景,构造函数内定义的方法每个实例独立
- 箭头函数会改变
this绑定,不适合作为对象方法 - 现代 JavaScript 推荐使用
class语法,本质仍是原型继承的语法糖






