javascript - 在文件之间拆分 Node.js 类扩展

标签 javascript node.js class

我正在尝试在 Node.js 中创建一个 Discord 机器人。我有一个主文件 bot.js,其中包含主控制流。我想将世界状态实现为一个类,并将该类上的操作拆分到其他文件中。但是,我不太确定如何做到这一点,特别是我必须重新组合扩展同一类的多个函数文件(让我们称它们为startup.js 和bios.js)的部分。

我是否应该有一个包含类定义的单独文件,以便我可以将其导入到两个帮助程序文件中?

common.js

module.exports = botState;

class botState {
    //class definition goes here
}

初始化.js

const common = require('./common');

class initializeState extends botState {
    constructor () {
        //it's a constructor; details not too important
    }

    function1 () {} //implementation not important

    function2 () {}
}

module.exports = initializeState;

chars.js

const common = require('./common');

class bioState extends botState {
    constructor () {
        //it's a constructor; details not too important
    }

    function3 () {} //implementation not important

    function4 () {}
}

module.exports = BioState;

bot.js

//main control flow is in this file
//I'd like to have a class that implements functions 1 through 4, but don't know how to do that.

我不知道如何实现 bot.js。可能有一些更好的结构来完全实现这一点。

最佳答案

听起来您正在尝试在同一文件或不同文件中进行一些多重继承,而 Javascript 不支持这种多重继承(请参阅此处的最后一节: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model )。

也就是说,您可以做的是利用原型(prototype)系统的工作原理。您可以将函数 1-4 与类定义分开编写,并将它们附加到您想要的类的原型(prototype)上。

function function1(){
  this.someValue = this.someOtherValue + this.someMethod();
  return 7;
}
// ... and other functions

BioState.prototype.function1 = function1;
InitializeState.prototype.function1 = function1;

这些函数在哪里定义或附加到类原型(prototype)并不重要——尽管为了清楚起见,在一个地方声明这些函数、将它们导入到每个需要它的类的文件中,并在导出类之前将它们附加到原型(prototype)是有意义的。

const { function1, function2 } = require('./common-functions');
class Blah {
//...
}
Blah.prototype.function1 = function1;
Blah.prototype.function2 = function2;
// You could also do this in the constructor as this.function1 = function1;

module.exports = Blah;

关于javascript - 在文件之间拆分 Node.js 类扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59656033/

相关文章:

javascript - 如何在 jqGrid 中加载详细网格时禁用主网格 rowSelect?

javascript - 在 if 语句上使用 Promises

node.js - node/express 中的 async/await 似乎不等待 Promise 解决

vb.net 类只读属性作为列表(T)

java - 将另一个类设置为主类 Android

javascript - 如果同一 Controller 在页面中使用两次,则停止反射(reflect)彼此的模型

javascript - 在 jQuery 中获取附加的 div id

node.js - webpack 捆绑针对 node.js 的代码

c++ - 将大括号内的 'this' 传递给 C++ 中的类的对象

javascript:避免浏览器在内容插入时滚动回顶部