Node.js中的面向对象编程最佳实践(面向对象.实践.编程.Node.js...)

wufei123 发布于 2024-10-13 阅读(92)

node.js中的面向对象编程最佳实践

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); // 1200
console.log(success); // true

以上就是Node.js中的面向对象编程最佳实践的详细内容,更多请关注知识资源分享宝库其它相关文章!

标签:  面向对象 实践 编程 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。