带有require的Node.js ES6类 [英] Node.js ES6 classes with require

查看:84
本文介绍了带有require的Node.js ES6类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经按照以下方式在 node.js 中创建了类和模块:

So up until now, i have created classes and modules in node.js the following way:

    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;






现在使用ES6,你可以实际的类就像这样:


Now with ES6, you are able to make "actual" classes just like this:

class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

现在,首先,我喜欢这个:)但它提出了一个问题。你如何结合使用 node.js 的模块结构?

Now, first of all, i love this :) but it raises a question. How do you use this combined with node.js's module structure?

假设你有一个班级在哪里希望使用模块为了演示说你想使用 fs

Say you have a class where you wish to use a module for the sake of demonstration say you wish to use fs

所以你创建你的文件:

so you create your file:

Animal.js

var fs = require('fs');
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

这是正确的方法吗?

另外,如何将此类公开给我的节点项目中的其他文件?如果你在一个单独的文件中使用它,你仍然可以扩展这个类吗?

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.

至于暴露你的课程,你可以 export 一个类就像其他任何东西一样:

As for exposing your classes, you can export a class just like anything else:

class Animal {...}
module.exports = Animal;

或更短的:

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 {
    ...
}

这篇关于带有require的Node.js ES6类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆