简体   繁体   English

你如何在另一个class中调用一个module.exports = function()里面的一个function?

[英]How do you call a function inside a module.exports = function () in another class?

In the following example, simply putting module.exports = {save} on the jsFileName.js file functions is not an option here, due to limitations on my codebase.在下面的示例中,由于我的代码库的限制,简单地将module.exports = {save}放在jsFileName.js文件函数上不是一个选项。 Is this possible to access the function from the export, inside of callFunctionFromAboveFile.js shown below?是否可以从如下所示的callFunctionFromAboveFile.js内部的导出访问 function? See the below example of how I'd like to access that function. I've searched all the other answers to questions similar but they all mention using the exports differently as I stated in my first line above.请参阅下面的示例,了解我想如何访问该 function。我已经搜索了所有其他类似问题的答案,但他们都提到使用导出的方式与我在上面第一行中所述的不同。

If there is a way to access it as it is shown, please share your answer or details as to why it's not possible.如果有显示的方法访问它,请分享您的答案或详细信息,说明为什么它不可能。 Also, other ways to handle this would be helpful but I can't change the class up much given the limitation to the codebase.此外,其他处理此问题的方法会有所帮助,但鉴于代码库的限制,我无法将 class 更改太多。

jsFileName.js js文件名.js

module.exports = function (JsFileName) {
    JsFileName.save = function (stuff) {}
}

callFunctionFromAboveFile.js callFunctionFromAboveFile.js

const JsFileName = require('jsFileName');
// TODO I'm not sure how this would call the save() w/out using exports differently.
// TODO I have to use exports as I've posted it in jsFileName.js

The default export of jsFileName.js is a function that adds functions to its parameter JsFileName . jsFileName.js 的默认导出是jsFileName.js ,它向其参数JsFileName添加函数。
Apparently, you can pass any object which is then modified to act as the module's exports.显然,您可以传递任何 object,然后将其修改为模块的导出。

That means: Pass any object you want to have the modules' functionality.这意味着:传递您想要拥有模块功能的任何 object。 Note that the object is not returned, so you have to keep the reference to it yourself.请注意,不会返回 object,因此您必须自己保留对它的引用。

// callFunctionFromAboveFile.js
const JsFileName = {};
require("jsFileName") // Get default export (the function)
  (JsFileName); // Call with any object you want to "enhance"

JsFileName.save(/*...*/);

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

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