面向对象编程

面向对象编程(OOP)是一种编程范式,它使用对象来组织代码。JavaScript是一种基于原型的面向对象语言,与传统的基于类的面向对象语言(如Java、C++)有所不同。

构造函数

构造函数用于创建对象实例:

javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log(`Hello, my name is ${this.name}.`);
  };
}

const person1 = new Person("John", 30);
const person2 = new Person("Jane", 25);

person1.greet(); // Hello, my name is John.
person2.greet(); // Hello, my name is Jane.

原型

每个JavaScript函数都有一个prototype属性,用于共享方法和属性:

javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// 将方法添加到原型
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

Person.prototype.getAge = function() {
  return this.age;
};

const person1 = new Person("John", 30);
const person2 = new Person("Jane", 25);

person1.greet(); // Hello, my name is John.
person2.greet(); // Hello, my name is Jane.

// 共享同一个方法实例
console.log(person1.greet === person2.greet); // true

原型链

JavaScript通过原型链实现继承:

javascript
function Animal(name) {
  this.name = name;
}

Animal.prototype.eat = function() {
  console.log(`${this.name} is eating.`);
};

function Dog(name, breed) {
  Animal.call(this, name); // 调用父构造函数
  this.breed = breed;
}

// 设置原型链
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// 添加狗特有的方法
Dog.prototype.bark = function() {
  console.log(`${this.name} is barking.`);
};

const dog = new Dog("Buddy", "Labrador");
dog.eat(); // Buddy is eating.
dog.bark(); // Buddy is barking.

ES6类

ES6引入了类语法,使面向对象编程更加直观:

javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }

  getAge() {
    return this.age;
  }
}

const person = new Person("John", 30);
person.greet(); // Hello, my name is John.

类的继承

使用extends关键字实现继承:

javascript
class Animal {
  constructor(name) {
    this.name = name;
  }

  eat() {
    console.log(`${this.name} is eating.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 调用父类构造函数
    this.breed = breed;
  }

  bark() {
    console.log(`${this.name} is barking.`);
  }
}

const dog = new Dog("Buddy", "Labrador");
dog.eat(); // Buddy is eating.
dog.bark(); // Buddy is barking.

静态方法

静态方法属于类本身,而不是实例:

javascript
class MathUtil {
  static add(a, b) {
    return a + b;
  }

  static subtract(a, b) {
    return a - b;
  }
}

console.log(MathUtil.add(2, 3)); // 5
console.log(MathUtil.subtract(5, 2)); // 3

getter和setter

getter和setter用于控制属性的访问和修改:

javascript
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  set fullName(name) {
    const [firstName, lastName] = name.split(" ");
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

const person = new Person("John", "Doe");
console.log(person.fullName); // John Doe

person.fullName = "Jane Smith";
console.log(person.firstName); // Jane
console.log(person.lastName); // Smith

面向对象编程原则

封装

将数据和方法封装在对象内部,隐藏实现细节:

javascript
class Counter {
  #count = 0; // 私有属性

  increment() {
    this.#count++;
  }

  decrement() {
    this.#count--;
  }

  getCount() {
    return this.#count;
  }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.#count); // SyntaxError: Private field '#count' must be declared in an enclosing class

继承

通过继承复用代码,创建层次结构:

javascript
// 参考前面的Animal和Dog类示例

多态

不同对象对同一方法的不同实现:

javascript
class Shape {
  area() {
    return 0;
  }
}

class Circle extends Shape {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius * this.radius;
  }
}

class Rectangle extends Shape {
  constructor(width, height) {
    super();
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }
}

const shapes = [new Circle(5), new Rectangle(4, 6)];
shapes.forEach(shape => console.log(shape.area()));
// 78.53981633974483
// 24

抽象

隐藏复杂实现,只暴露必要的接口:

javascript
class Database {
  // 抽象方法
  connect() {
    throw new Error("connect() method must be implemented");
  }

  query(sql) {
    throw new Error("query() method must be implemented");
  }
}

class MySQLDatabase extends Database {
  connect() {
    console.log("连接到MySQL数据库");
  }

  query(sql) {
    console.log(`执行MySQL查询: ${sql}`);
  }
}

class MongoDB extends Database {
  connect() {
    console.log("连接到MongoDB数据库");
  }

  query(query) {
    console.log(`执行MongoDB查询: ${JSON.stringify(query)}`);
  }
}

学习资源


继续学习:异步编程

最后更新:2026-02-08