JS梳理之ES6面向对象

面向对象
es5
公有方法 通过原型原型链实现
私有属性 通过闭包实现 外部无法直接访问 需要通过内部方法访问
公共属性 this实现

class

定义、继承、封装、多态、静态属性

class BankAccount {
    #balance; // 私有字段

    constructor(initialBalance) {
        this.#balance = initialBalance;
    }

    deposit(amount) {
        this.#balance += amount;
    }

    getBalance() {
        return this.#balance;
    }
}

const account2 = new BankAccount(100);
account2.deposit(50);
console.log(account2.getBalance()); // 输出: 150
class Cat extends Animal {
    speak() {
        console.log(`${this.name} meows.`);
    }
}

const animals = [new Dog('Rex'), new Cat('Whiskers')];

animals.forEach(animal => {
    animal.speak(); // 输出: Rex barks. 和 Whiskers meows.
});
class MathUtils {
    static add(a, b) {
        return a + b;
    }
}

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

this指向
构造函数constructor中指向新实例本身
方法中会可能会丢失,推荐使用箭头函数
也可以再constructor中使用bind进行绑定

posted @ 2025-03-27 22:55  张正1998  阅读(6)  评论(0)    收藏  举报