
Node.js 中的面向对象编程最佳实践
类和对象
类定义:
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); // 1200console.log(success); // true
以上就是Node.js中的面向对象编程最佳实践的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1460792.html
微信扫一扫
支付宝扫一扫