繁体   English   中英

JS - 如何在同一文件中访问module.exports函数

[英]JS - How to access a module.exports function in the same file

我有一个看起来像这样的函数:

module.exports = myFunction() {
  //do some stuff
}

我可以使用var myFunction = require(.thepath.js)从其他文件中访问它

但是,我如何从它创建的文件中访问它。

我已经尝试了myFunction()this.myFunction()但都没有工作。

谢谢

您可以将其保存到变量然后导出变量,如下所示:

// Create the function
const myFunction = function() {

}

// Call the function
myFunction();

// Export the function
module.exports = myFunction

如果你不想在同一个文件中调用它,你可以在这里使用anonyomous函数

module.exports = function (){
    // do some stuff
}

只要您给它命名,就可以使用它的名称来调用它。

module.exports = function myFunction(){

//做一些东西 }

myFunction的()

对不起,我记得错了。 这里存在一个范围问题,可以通过从赋值中单独定义函数来解决。

function myFunction (){
    // do some stuff
}
module.exports = myFunction

myFunction()
var func = module.exports = myFunction(){
   //do some stuff here
}

现在您可以通过变量访问。

暂无
暂无

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

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