Skip to content

对象、类与面向对象编程

理解对象

1. 对象的创建方式

字面量语法
let person = {
  name: 'John',
  age: 30
};
构造函数
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Object.create()
let person = Object.create(null);
person.name = 'John';
person.age = 30;

2. 属性特性

数据属性

  • [[Configurable]]
  • [[Enumerable]]
  • [[Writable]]
  • [[Value]]

访问器属性

  • [[Configurable]]
  • [[Enumerable]]
  • [[Get]]
  • [[Set]]

原型与继承

1. 原型链

实例对象
person
name: 'John'
age: 30
Person.prototype
constructor: Person
sayHello()
Object.prototype
toString()
valueOf()

2. 类的实现

基类定义
class Person {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log(`Hello, I'm ${this.name}`);
  }
}
派生类定义
class Employee extends Person {
  constructor(name, role) {
    super(name);
    this.role = role;
  }
  work() {
    console.log(`${this.name} is working as ${this.role}`);
  }
}

实际应用示例

1. 组件系统

javascript
class Component {
    constructor(props = {}) {
        this.props = props;
        this.state = {};
    }
    
    setState(newState) {
        this.state = { ...this.state, ...newState };
        this.render();
    }
    
    render() {
        throw new Error('Render method must be implemented');
    }
}

class Button extends Component {
    constructor(props) {
        super(props);
        this.state = { clicked: 0 };
    }
    
    render() {
        return `
            <button onclick="this.handleClick()">
                Clicked ${this.state.clicked} times
            </button>
        `;
    }
    
    handleClick() {
        this.setState({ clicked: this.state.clicked + 1 });
    }
}

2. 状态管理

javascript
class Store {
    #state = {};
    #listeners = new Set();
    
    constructor(initialState = {}) {
        this.#state = initialState;
    }
    
    getState() {
        return { ...this.#state };
    }
    
    setState(newState) {
        this.#state = { ...this.#state, ...newState };
        this.#notifyListeners();
    }
    
    subscribe(listener) {
        this.#listeners.add(listener);
        return () => this.#listeners.delete(listener);
    }
    
    #notifyListeners() {
        for (const listener of this.#listeners) {
            listener(this.#state);
        }
    }
}

最佳实践

  1. 类的设计原则

    • 单一职责原则
    • 开放封闭原则
    • 里氏替换原则
    • 接口隔离原则
    • 依赖倒置原则
  2. 性能优化

    • 避免深层原型链
    • 合理使用私有字段
    • 使用工厂模式创建对象
  3. 代码组织

    • 模块化设计
    • 合理的继承层次
    • 清晰的接口定义

编码建议

  • 优先使用类语法而不是原型继承
  • 使用私有字段保护数据
  • 合理使用静态方法
  • 避免过度继承

练习题

  1. 实现一个带有私有属性的计数器类。
  2. 创建一个简单的事件发布订阅系统。
  3. 实现一个支持链式调用的 DOM 操作类。
  4. 设计一个基于类的动画系统。

扩展阅读

本站内容采用 "署名-非商业性使用-禁止演绎 4.0 国际许可协议" 进行许可