快速.JS无法识别所需的js文件的功能

Express.JS not recognizing required js file's functions

本文关键字:js 文件 功能 JS 识别 快速      更新时间:2023-09-26

尽管我已经导入了包含我将使用的函数的JS文件,Node.JS说它是未定义的。

require('./game_core.js');
Users/dasdasd/Developer/optionalassignment/games.js:28
    thegame.gamecore = new game_core( thegame );
                       ^
ReferenceError: game_core is not defined

你知道出了什么问题吗?Game_core包括以下功能:

var game_core = function(game_instance){....};

添加到game_core.js末尾:

module.exports = {  
    game_core : game_core  
}  

到游戏.js:

var game_core = require('./game_core').game_core(game_istance);

在 Node 中要求模块不会将其内容添加到全局范围。每个模块都包装在自己的作用域中,因此您必须导出公共名称:

// game_core.js
module.exports = function (game_instance){...};

然后在主脚本中保留对导出对象的引用:

var game_core = require('./game_core.js');
...
thegame.gamecore = new game_core( thegame );

您可以在文档中阅读有关它的更多信息:http://nodejs.org/api/modules.html#modules_modules

另一种方法:

if( 'undefined' != typeof global ) {
    module.exports = global.game_core = game_core;
}