
类定义:
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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号