乐闻世界logo
搜索文章和话题

Nodejs 中的如何实现 oop 面向对象编程?

7 个月前提问
5 个月前修改
浏览次数55

6个答案

1
2
3
4
5
6

在Node.js中实现面向对象编程(OOP)的方法主要是通过使用JavaScript的类和原型继承特性。以下是实现OOP的几个步骤:

1. 定义类

在ES6中引入了class关键字,可以使定义类更加直观。类是对象的蓝图,可以定义属性和方法。

javascript
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } }

2. 创建对象实例

使用new关键字从类创建对象实例。

javascript
const person1 = new Person('Alice', 30); person1.greet(); // 输出: Hello, my name is Alice and I am 30 years old.

3. 继承

可以通过extends关键字使一个类继承另一个类的特性。

javascript
class Employee extends Person { constructor(name, age, jobTitle) { super(name, age); // 调用父类的构造器 this.jobTitle = jobTitle; } work() { console.log(`${this.name} is working as a ${this.jobTitle}.`); } } const employee1 = new Employee('Bob', 25, 'Software Developer'); employee1.greet(); // 输出: Hello, my name is Bob and I am 25 years old. employee1.work(); // 输出: Bob is working as a Software Developer.

4. 封装

封装是OOP中的一个核心概念,意味着将对象的状态和行为包含在内部,并只暴露有限的接口与外界通信。

javascript
class BankAccount { #balance; // 私有属性,使用 # 标记 constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount <= this.#balance) { this.#balance -= amount; } } getBalance() { return this.#balance; } } const account = new BankAccount(1000); account.deposit(500); console.log(account.getBalance()); // 输出: 1500

在这个例子中,#balance是一个私有属性,它不可以直接从类的外部访问,而只能通过类的方法来操作。

5. 多态

多态性意味着子类可以定义一个与父类相同的方法,但具有不同的行为。

javascript
class Animal { speak() { console.log('Animal speaks'); } } class Dog extends Animal { speak() { console.log('Woof woof'); } } const animal = new Animal(); const dog = new Dog(); animal.speak(); // 输出: Animal speaks dog.speak(); // 输出: Woof woof

在这个例子中,Dog类重写了Animal类的speak方法,实现了多态。

通过这些步骤,我们可以在Node.js中实现面向对象编程的基本概念,包括类的定义、继承、封装和多态。这些原则有助于组织和模块化代码,使其更易于理解和维护。

2024年6月29日 12:07 回复

This is an example that works out of the box. If you want less "hacky", you should use inheritance library or such.

Well in a file animal.js you would write:

shell
var method = Animal.prototype; function Animal(age) { this._age = age; } method.getAge = function() { return this._age; }; module.exports = Animal;

To use it in other file:

shell
var Animal = require("./animal.js"); var john = new Animal(3);

If you want a "sub class" then inside mouse.js:

shell
var _super = require("./animal.js").prototype, method = Mouse.prototype = Object.create( _super ); method.constructor = Mouse; function Mouse() { _super.constructor.apply( this, arguments ); } //Pointless override to show super calls //note that for performance (e.g. inlining the below is impossible) //you should do //method.$getAge = _super.getAge; //and then use this.$getAge() instead of super() method.getAge = function() { return _super.getAge.call(this); }; module.exports = Mouse;

Also you can consider "Method borrowing" instead of vertical inheritance. You don't need to inherit from a "class" to use its method on your class. For instance:

shell
var method = List.prototype; function List() { } method.add = Array.prototype.push; ... var a = new List(); a.add(3); console.log(a[0]) //3;
2024年6月29日 12:07 回复

As Node.js community ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers in a timely manner.

You can take a look at JavaScript classes. MDN link to JS classes In the ECMAScript 6 JavaScript classes are introduced, this method provide easier way to model OOP concepts in Javascript.

Note : JS classes will work in only strict mode.

Below is some skeleton of class,inheritance written in Node.js ( Used Node.js Version v5.0.0 )

Class declarations :

shell
'use strict'; class Animal{ constructor(name){ this.name = name ; } print(){ console.log('Name is :'+ this.name); } } var a1 = new Animal('Dog');

Inheritance :

shell
'use strict'; class Base{ constructor(){ } // methods definitions go here } class Child extends Base{ // methods definitions go here print(){ } } var childObj = new Child();
2024年6月29日 12:07 回复

This is the best video about Object-Oriented JavaScript on the internet:

The Definitive Guide to Object-Oriented JavaScript

Watch from beginning to end!!

Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.

With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.

Screenshot from the video showing how to write and instantiate a Javascript class/subclass:

enter image description here

2024年6月29日 12:07 回复

In the Javascript community, lots of people argue that OOP should not be used because the prototype model does not allow to do a strict and robust OOP natively. However, I don't think that OOP is a matter of langage but rather a matter of architecture.

If you want to use a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf. It provides all needed features for a strong OOP code (classes, interfaces, inheritance, dependency-injection, ...). It also allows you to use the same classes on both the server (node) and client (browser) sides. Moreover, you can code your own danf modules and share them with anybody thanks to Npm.

2024年6月29日 12:07 回复

你的答案