类定义:
class Person { constructor(name, age) { this.name = name; this.age = age; } }
对象创建:
const person = new Person('John', 30);
父类定义:
class Employee { constructor(name, salary) { this.name = name; this.salary = salary; } }
子类定义(继承 Employee):
class Manager extends Employee { constructor(name, salary, department) { super(name, salary); this.department = department; } }
私有成员:
class Person { #privateProperty = 'secret'; }
私有方法:
class Person { #privateMethod() {} }
接口定义:
interface Animal { speak(): string; }
实现接口:
class Dog implements Animal { speak() { return 'Woof!'; } }
使用多态:
const animals: Animal[] = [new Dog(), new Cat()]; animals.forEach((animal) => console.log(animal.speak()));
// 账户类 class Account { constructor(name, balance) { this.name = name; this.balance = balance; } deposit(amount) { this.balance += amount; } withdraw(amount) { if (amount <= this.balance) { this.balance -= amount; return true; } return false; } } // 账户列表 const accounts = [ new Account('John', 1000), new Account('Jane', 500), ]; // 操作账户 accounts[0].deposit(200); const success = accounts[1].withdraw(300); console.log(accounts[0].balance); // 1200 console.log(success); // true
以上就是Node.js中的面向对象编程最佳实践的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号