
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;
}
}封装
私有成员:
本书全面介绍PHP脚本语言和MySOL数据库这两种目前最流行的开源软件,主要包括PHP和MySQL基本概念、PHP扩展与应用库、日期和时间功能、PHP数据对象扩展、PHP的mysqli扩展、MySQL 5的存储例程、解发器和视图等。本书帮助读者学习PHP编程语言和MySQL数据库服务器的最佳实践,了解如何创建数据库驱动的动态Web应用程序。
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







