跳转到内容

JavaScript面向对象基础

来自代码酷

JavaScript面向对象基础[编辑 | 编辑源代码]

面向对象编程(Object-Oriented Programming, OOP)是一种以对象为核心的编程范式,JavaScript通过原型继承构造函数等机制实现OOP。本章将详细介绍JavaScript中的面向对象基础概念,包括对象、构造函数、原型链等核心内容。

1. 对象基础[编辑 | 编辑源代码]

在JavaScript中,对象是键值对的集合,用于存储和组织数据。对象可以通过字面量、构造函数或`class`语法创建。

1.1 对象字面量[编辑 | 编辑源代码]

最简单的创建对象的方式是使用对象字面量

// 创建一个对象字面量
const person = {
    name: "Alice",
    age: 25,
    greet: function() {
        return `Hello, my name is ${this.name}!`;
    }
};

console.log(person.name); // 输出: Alice
console.log(person.greet()); // 输出: Hello, my name is Alice!

解释:

  • `person`是一个对象,包含属性(`name`、`age`)和方法(`greet`)。
  • `this`关键字指向当前对象(即`person`)。

1.2 动态添加属性[编辑 | 编辑源代码]

JavaScript对象是动态的,可以随时添加或修改属性:

person.job = "Developer"; // 添加新属性
person.greet = function() {
    return `Hi, I'm ${this.name} and I work as a ${this.job}!`;
};

console.log(person.greet()); // 输出: Hi, I'm Alice and I work as a Developer!

2. 构造函数与实例[编辑 | 编辑源代码]

构造函数用于创建多个相似的对象。通过`new`关键字调用构造函数时,会创建一个新实例。

2.1 定义构造函数[编辑 | 编辑源代码]

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        return `Hello, I'm ${this.name}!`;
    };
}

const alice = new Person("Alice", 25);
const bob = new Person("Bob", 30);

console.log(alice.greet()); // 输出: Hello, I'm Alice!
console.log(bob.age); // 输出: 30

问题:每个实例都会创建独立的`greet`方法,浪费内存。 解决方案:使用原型(prototype)共享方法。

3. 原型与继承[编辑 | 编辑源代码]

JavaScript通过原型链实现继承。每个对象都有一个原型(`__proto__`),用于共享属性和方法。

3.1 原型方法[编辑 | 编辑源代码]

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

// 将方法添加到原型
Person.prototype.greet = function() {
    return `Hello, I'm ${this.name}!`;
};

const alice = new Person("Alice", 25);
console.log(alice.greet()); // 输出: Hello, I'm Alice!

优势:所有实例共享同一个`greet`方法,节省内存。

3.2 原型链图示[编辑 | 编辑源代码]

graph LR A[alice实例] -->|__proto__| B[Person.prototype] B -->|__proto__| C[Object.prototype] C -->|__proto__| D[null]

解释:

  • `alice.__proto__`指向`Person.prototype`。
  • `Person.prototype.__proto__`指向`Object.prototype`(所有对象的基类)。
  • 最终原型链顶端是`null`。

4. Class语法(ES6)[编辑 | 编辑源代码]

ES6引入`class`语法,简化了OOP的实现:

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

    greet() {
        return `Hello, I'm ${this.name}!`;
    }
}

const alice = new Person("Alice", 25);
console.log(alice.greet()); // 输出: Hello, I'm Alice!

注意:`class`是语法糖,底层仍基于原型。

5. 实际应用案例[编辑 | 编辑源代码]

5.1 购物车系统[编辑 | 编辑源代码]

使用OOP实现购物车功能:

class Cart {
    constructor() {
        this.items = [];
    }

    addItem(product, quantity) {
        this.items.push({ product, quantity });
    }

    calculateTotal() {
        return this.items.reduce(
            (total, item) => total + (item.product.price * item.quantity), 0
        );
    }
}

const cart = new Cart();
cart.addItem({ name: "Book", price: 20 }, 2);
cart.addItem({ name: "Pen", price: 5 }, 3);

console.log(cart.calculateTotal()); // 输出: 55 (20*2 + 5*3)

5.2 游戏角色系统[编辑 | 编辑源代码]

class Character {
    constructor(name, health) {
        this.name = name;
        this.health = health;
    }

    attack(target) {
        target.health -= 10;
        return `${this.name} attacks ${target.name}!`;
    }
}

const hero = new Character("Hero", 100);
const enemy = new Character("Enemy", 50);

console.log(hero.attack(enemy)); // 输出: Hero attacks Enemy!
console.log(enemy.health); // 输出: 40

6. 总结[编辑 | 编辑源代码]

  • JavaScript通过对象构造函数原型实现OOP。
  • `class`语法是原型的语法糖,更易读写。
  • 原型链是JavaScript继承的核心机制。
  • OOP适合模块化开发,如购物车、游戏角色等场景。

掌握这些基础后,可以进一步学习封装多态设计模式等高级主题。