Skip to content

JavaScript 类

类的基础

1. 类声明

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

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

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

2. 类表达式

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

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

const person = new Person('John', 30);

类的属性和方法

1. 构造函数

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

2. 实例属性

javascript
class Person {
    // 新的实例属性语法(ES2022)
    name = '';
    age = 0;

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

3. 实例方法

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

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

    celebrateBirthday() {
        this.age++;
        console.log(`Happy birthday! Now I'm ${this.age} years old`);
    }
}

4. Getter 和 Setter

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

    get fullName() {
        return `${this._firstName} ${this._lastName}`;
    }

    set fullName(value) {
        const [firstName, lastName] = value.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.fullName); // 'Jane Smith'

类的特性

1. 提升

javascript
// 错误:不能在声明前使用类
const person = new Person(); // ReferenceError

class Person {
    constructor() {
        this.name = 'John';
    }
}

2. 严格模式

javascript
class Person {
    constructor() {
        // 类内部自动运行在严格模式下
        // 下面的代码会抛出错误
        // undeclaredVar = 'error';
    }
}

3. 类的 typeof

javascript
class Person {}
console.log(typeof Person); // 'function'

与函数构造函数的比较

1. 类构造函数

javascript
// 类声明
class Person {
    constructor(name) {
        this.name = name;
    }

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

2. 函数构造函数

javascript
// 函数构造函数等效实现
function Person(name) {
    this.name = name;
}

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

最佳实践

  1. 使用类声明而不是类表达式
  2. 构造函数中初始化所有实例属性
  3. 使用 getter 和 setter 控制属性访问
  4. 使用类的静态方法代替全局工具函数
  5. 了解类只是函数和原型继承的语法糖
  6. 在类方法中使用箭头函数处理回调中的 this
  7. 优先使用组合而不是继承