为什么我不能从单独的.js文件中调用任何函数

Why can't I call any functions from a separate .js file?

本文关键字:文件 调用 任何 函数 js 不能 单独 为什么      更新时间:2023-09-26

如果我有以下main.js文件:

require('./test.js');
$(document).ready(function(){
    testFunction();
});

然后与main.js位于同一目录中的coorespond test.js文件:

function testFunction()
{
    console.log('from test.js');
}

我收到错误:

未捕获的类型错误:测试函数不是函数

如果我尝试将 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();

还有许多其他选项和可能性,请务必阅读文档。