简体   繁体   English

带有 require 的 Node.js ES6 类

[英]Node.js ES6 classes with require

So up until now, i have created classes and modules in node.js the 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?你如何结合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 :)我希望你们中的一些人能够回答这些问题:)

Yes, your example would work fine.是的,您的示例可以正常工作。

As for exposing your classes, you can export a 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 {
    ...
}

Just treat the ES6 class name the same as you would have treated the constructor name in the ES5 way.只需将 ES6 类名称与您在 ES5 方式中处理构造函数名称相同即可。 They are one and the same.他们是一样的。

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 Animal like the constructor of your object (the same as you would have done in ES5).您可以将Animal视为对象的构造函数(就像您在 ES5 中所做的那样)。 You can export the constructor.您可以导出构造函数。 You can call the constructor with new Animal() .您可以使用new Animal()调用构造函数。 Everything is the same for using it.使用它的一切都是一样的。 Only the declaration syntax is different.只有声明语法不同。 There's even still an Animal.prototype that has all your methods on it.甚至还有一个Animal.prototype有你所有的方法。 The ES6 way really does create the same coding result, just with fancier/nicer syntax. 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 .Animal property 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();

The ES6 way of require is import . ES6 的 require 方式是import You can export your class and import it somewhere else using import { ClassName } from 'path/to/ClassName' syntax.您可以使用import { ClassName } from 'path/to/ClassName'语法export您的类并将其导入其他地方。

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';

Using Classes in Node -在节点中使用类 -

Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class.这里我们需要 ReadWrite 模块并调用 makeObject(),它返回 ReadWrite 类的对象。 Which we are using to call the methods.我们用来调用方法。 index.js索引.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

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 classObject to access the actual class variables在此之后,您可以使用classObject访问实际的类变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM