如果我有以下 main.js
文件:
require('./test.js');
$(document).ready(function(){
testFunction();
});
然后是与 main.js
位于同一目录中的相应 test.js
文件:
function testFunction()
{
console.log('from test.js');
}
我收到错误:
Uncaught TypeError: testFunction is not a function
如果我尝试将 require 语句设置为变量 x
,然后在我的主 js 文件中调用 x.testFunction,那么我会得到相同的错误,但使用 x.testFunction
.
我该如何让它发挥作用?我需要能够从单独的 js 文件调用函数。
最佳答案
您需要从包含该函数的文件中导出:
function fooBar() {
console.log('hi');
}
module.exports = fooBar;
然后,您可以在其他文件中使用它,例如:
var foo = require('./fooBar');
foo();
如果你想从另一个文件导出多个函数,你也可以使用一个对象:
module.exports = {
fooBar: fooBar,
Baz: Baz
};
并使用它:
foo.fooBar();
foo.Baz();
还有许多其他选项和可能性,请务必也阅读文档。
关于javascript - 为什么我无法从单独的 .js 文件调用任何函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35243435/