Javascript 带有 require 的 Node.js ES6 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42684177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js ES6 classes with require
提问by Marc Rasmussen
So up until now, i have created classes and modules in node.jsthe following way:
所以到目前为止,我已经node.js通过以下方式创建了类和模块:
var fs = require('fs');
var animalModule = (function () {
/**
* Constructor initialize object
* @constructor
*/
var Animal = function (name) {
this.name = name;
};
Animal.prototype.print = function () {
console.log('Name is :'+ this.name);
};
return {
Animal: Animal
}
}());
module.exports = animalModule;
Now with ES6, you are able to make "actual" classes just like this:
现在使用 ES6,您可以像这样创建“实际”类:
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
Now, first of all, i love this :) but it raises a question. How do you use this combined with node.js's module structure?
现在,首先,我喜欢这个 :) 但它提出了一个问题。你如何将 this 与node.js的模块结构结合使用?
Say you have a class where you wish to use a module for the sake of demonstration say you wish to use fs
假设您有一个类,为了演示,您希望在其中使用一个模块 假设您希望使用 fs
so you create your file:
所以你创建你的文件:
Animal.js
动物.js
var fs = require('fs');
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
Would this be the right way?
这是正确的方法吗?
Also, how do you expose this class to other files within my node project? And would you still be able to extend this class if you're using it in a separate file?
另外,您如何将此类公开给我的节点项目中的其他文件?如果你在一个单独的文件中使用它,你仍然能够扩展这个类吗?
I hope some of you will be able to answer these questions :)
我希望你们中的一些人能够回答这些问题:)
回答by rossipedia
Yes, your example would work fine.
是的,您的示例可以正常工作。
As for exposing your classes, you can exporta class just like anything else:
至于公开您的类,您可以export像其他任何东西一样创建类:
class Animal {...}
module.exports = Animal;
Or the shorter:
或者更短的:
module.exports = class Animal {
};
Once imported into another module, then you can treat it as if it were defined in that file:
一旦导入到另一个模块中,您就可以将其视为在该文件中定义的:
var Animal = require('./Animal');
class Cat extends Animal {
...
}
回答by jfriend00
Just treat the ES6 class name the same as you would have treated the constructor name in the ES5 way. They are one and the same.
只需将 ES6 类名称与您在 ES5 方式中处理构造函数名称相同即可。他们是一样的。
The ES6 syntax is just syntactic sugar and creates exactly the same underlying prototype, constructor function and objects.
ES6 语法只是语法糖,它创建了完全相同的底层原型、构造函数和对象。
So, in your ES6 example with:
因此,在您的 ES6 示例中:
// animal.js
class Animal {
...
}
var a = new Animal();
module.exports = {Animal: Animal};
You can just treat Animallike the constructor of your object (the same as you would have done in ES5). You can export the constructor. You can call the constructor with new Animal(). Everything is the same for using it. Only the declaration syntax is different. There's even still an Animal.prototypethat has all your methods on it. The ES6 way really does create the same coding result, just with fancier/nicer syntax.
您可以Animal像对待对象的构造函数一样对待(就像在 ES5 中所做的那样)。您可以导出构造函数。您可以使用new Animal(). 使用它的一切都是一样的。只有声明语法不同。甚至还有一个里面Animal.prototype有你所有的方法。ES6 方式确实创建了相同的编码结果,只是使用了更好/更好的语法。
On the import side, this would then be used like this:
在进口方面,这将像这样使用:
const Animal = require('./animal.js').Animal;
let a = new Animal();
This scheme exports the Animal constructor as the .Animalproperty which allows you to export more than one thing from that module.
该方案将 Animal 构造函数.Animal导出为允许您从该模块中导出多个内容的属性。
If you don't need to export more than one thing, you can do this:
如果您不需要导出不止一件事,您可以这样做:
// animal.js
class Animal {
...
}
module.exports = Animal;
And, then import it with:
然后,使用以下命令导入它:
const Animal = require('./animal.js');
let a = new Animal();
回答by Fan Jin
The ES6 way of require is import. You can exportyour class and import it somewhere else using import { ClassName } from 'path/to/ClassName'syntax.
ES6 的 require 方式是import. 您可以export使用import { ClassName } from 'path/to/ClassName'语法将类导入到其他地方。
import fs from 'fs';
export default class Animal {
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
import Animal from 'path/to/Animal.js';
回答by Nayan Patel
Using Classes in Node -
在节点中使用类 -
Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class. Which we are using to call the methods. index.js
这里我们需要 ReadWrite 模块并调用 makeObject(),它返回 ReadWrite 类的对象。我们用来调用方法。 索引.js
const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();
class Start {
constructor() {
const server = app.listen(8081),
host = server.address().address,
port = server.address().port
console.log("Example app listening at http://%s:%s", host, port);
console.log('Running');
}
async route(req, res, next) {
const result = await ReadWrite.readWrite();
res.send(result);
}
}
const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;
ReadWrite.js
读写.js
Here we making a makeObject method, which makes sure that a object is returned, only if a object is not available.
这里我们创建了一个 makeObject 方法,它确保只有在对象不可用时才返回对象。
class ReadWrite {
constructor() {
console.log('Read Write');
this.x;
}
static makeObject() {
if (!this.x) {
this.x = new ReadWrite();
}
return this.x;
}
read(){
return "read"
}
write(){
return "write"
}
async readWrite() {
try {
const obj = ReadWrite.makeObject();
const result = await Promise.all([ obj.read(), obj.write()])
console.log(result);
check();
return result
}
catch(err) {
console.log(err);
}
}
}
module.exports = ReadWrite;
For more explanation go to https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74
有关更多解释,请访问https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74
回答by Burhan Maseel
In class file you can either use:
在类文件中,您可以使用:
module.exports = class ClassNameHere {
print() {
console.log('In print function');
}
}
or you can use this syntax
或者您可以使用此语法
class ClassNameHere{
print(){
console.log('In print function');
}
}
module.exports = ClassNameHere;
On the other hand to use this class in any other file you need to do these steps.
First require that file using this syntax:
const anyVariableNameHere = require('filePathHere');
另一方面,要在任何其他文件中使用此类,您需要执行这些步骤。首先使用以下语法要求该文件:
const anyVariableNameHere = require('filePathHere');
Then create an object
const classObject = new anyVariableNameHere();
然后创建一个对象
const classObject = new anyVariableNameHere();
After this you can use classObjectto access the actual class variables
在此之后,您可以使用classObject访问实际的类变量

