掌握 ES6 Class:从入门到精通

123 阅读1分钟

简介: 在 JavaScript 的历史中,ES6(ECMAScript 2015)引入了许多新特性,其中 Class 是一个重要的概念。Class 提供了一种更简洁、更面向对象的方式来定义对象和构造函数。本文将带你从基础到高级,彻底弄懂 ES6 的 Class,并通过具体例子让你掌握其使用。


1. Class 基础

在 ES6 之前,JavaScript 使用构造函数和原型链来模拟类和继承。ES6 的 Class 语法提供了一种更直观的方式来定义类和对象。以下是基本的 Class 定义:

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

    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

const person = new Person('Alice', 30);
person.greet();  // 输出: Hello, my name is Alice and I am 30 years old.

2. Class 继承

继承是面向对象编程中的一个核心概念,ES6 的 Class 也支持继承。通过 extends 关键字,一个类可以继承另一个类的属性和方法。

class Student extends Person {
    constructor(name, age, studentId) {
        super(name, age);
        this.studentId = studentId;
    }

    introduce() {
        super.greet();
        console.log(`I am a student with ID ${this.studentId}.`);
    }
}

const student = new Student('Bob', 22, 'S123');
student.introduce();  // 输出: Hello, my name is Bob and I am 22 years old. I am a student with ID S123.

3. Getter 和 Setter

Getter 和 Setter 是一种访问器,允许你定义一个方法来获取(getter)或设置(setter)一个属性的值。

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

    get name() {
        return this._name;
    }

    set name(value) {
        this._name = value;
    }

    get age() {
        return this._age;
    }

    set age(value) {
        if (value > 0) {
            this._age = value;
        } else {
            console.log('Age must be positive');
        }
    }
}

const person = new Person('Alice', 30);
console.log(person.name);  // 输出: Alice
person.name = 'Bob';
console.log(person.name);  // 输出: Bob
person.age = -5;  // 输出: Age must be positive

4. 静态方法

静态方法可以通过类直接调用,不需要实例化对象。它们常用于工具函数或与实例无关的方法。

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

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

console.log(MathUtils.add(5, 3));  // 输出: 8
console.log(MathUtils.subtract(5, 3));  // 输出: 2

5. 私有属性和方法

虽然 JavaScript 没有真正的私有属性,但可以通过命名约定(使用下划线 _)来模拟私有属性。

class Person {
    #name;
    #age;

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

    greet() {
        console.log(`Hello, my name is ${this.#name} and I am ${this.#age} years old.`);
    }
}

const person = new Person('Alice', 30);
person.greet();  // 输出: Hello, my name is Alice and I am 30 years old.

6. 总结

ES6 的 Class 提供了一种更简洁、更面向对象的方式来定义对象和构造函数。通过本文的示例,你可以看到如何定义类、使用继承、定义访问器、静态方法以及模拟私有属性。希望这些知识能帮助你更好地理解和使用 ES6 的 Class。