javascript - 带有 require 的 Node.js ES6 类

标签 javascript node.js ecmascript-6

到目前为止,我已经在 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;

现在使用 ES6,您可以像这样创建“实际”类:

class Animal{

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

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

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

假设您有一个类,您希望在其中使用模块以进行演示,假设您希望使用 fs

所以你创建你的文件:


Animal.js

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

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

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

这是正确的方法吗?

另外,您如何将此类公开给我的 Node 项目中的其他文件?如果你在一个单独的文件中使用它,你还能扩展这个类吗?

我希望你们中的一些人能够回答这些问题:)

最佳答案

是的,您的示例可以正常工作。

至于公开你的类,你可以像其他任何东西一样export一个类:

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

或更短的:

module.exports = class Animal {

};

一旦导入到另一个模块中,您就可以将其视为已在该文件中定义:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

关于javascript - 带有 require 的 Node.js ES6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42684177/

相关文章:

javascript - 调用父类中被重写的函数

javascript - 悬停时淡入/淡出背景图像

node.js - 刚刚开始新项目,当我运行 npm run dev 时,它在终端中抛出错误

javascript - 在主干应用程序中获取以前的路由器/url

javascript - Socket.io 套接字位于哪个房间?

javascript - 如何使用 Blockchain 的 API 跟踪比特币交易

javascript - 在 ECMAScript 2015 中调用 Reflect.apply() 比调用 Function.prototype.apply() 有什么好处吗?

javascript - 未捕获的类型错误 : Cannot read property 'type' of undefined at start of switch function

javascript - 无法在 Angular 4 中绑定(bind)属性

javascript - bignumber.js 中的 `c` 、 `e` 和 `s` 是什么意思?