【问题标题】:Access global variable outside of anonymous function in JavaScript using require使用 require 在 JavaScript 中访问匿名函数之外的全局变量
【发布时间】:2015-08-08 20:06:11
【问题描述】:

我正在开发一个 HTML5 实时多人游戏,我有一个使用 p2 库运行游戏物理的 game_core.js 文件。我想在客户端和权威服务器上运行这个文件来进行预测。这是构造函数和 module.exports:

function gameCore() {
    this.world = new p2.World({gravity:[0, 0]});
    this.players = {};
    this.step = 1/60;
}

...

module.exports = gameCore;

由于我在 index.html 中加载 p2.js 文件

<script type="text/javascript" src="lib/p2.js"></script>
<script type="text/javascript" src="game_client.js"></script>
<script type="text/javascript" src="game_core.js"></script>

构造函数找到 p2 对象,一切正常。但是我的问题是当我尝试在服务器上运行这个文件时,因为我找不到访问 p2 对象的正确方法,它是 game_server.js 上的一个全局变量:

var
    io              = require('socket.io'),
    express         = require('express'),
    UUID            = require('node-uuid'),
    p2              = require('p2'),
    verbose         = false,
    http            = require('http'),
    app             = express(),
    config          = require('./config.json'),
    gameCore        = require('./game_core.js'),
    server          = http.createServer(app);

var world = new gameCore();

我收到此错误:

this.world = new p2.World({gravity:[0, 0]});
                         ^
ReferenceError: p2 is not defined

如果我在 gameCore 上创建一个 p2 属性,在构造函数中将 world 保留为 null,将全局 p2 分配给 gameCore 的 p2,然后使用 init 函数将正确的值分配给 world

function gameCore() {
    this.p2 = null;
    this.world = null;
    this.players = {};
    this.step = 1/60;
}

gameCore.prototype.init = function() {   
    this.world = new this.p2.World({gravity:[0, 0]});
}

它有效,但因为我需要在其他类的 gameCore 上执行此操作,所以我得到了堆栈溢出。如果我使用

var p2 = require('p2');

在 gameCore 上它可以工作,但客户端抱怨使用 require。

我是 JavaScript 新手,但我研究过闭包、匿名函数和许多类似的疑问。不幸的是,我还不能解决这个问题。

【问题讨论】:

  • @tom,解决了我的问题,谢谢!但是如果有人知道另一种解决方案而不将我的脚本捆绑在一个文件中,我想知道。
  • 您是否有不想捆绑脚本的原因?在开发中,您应该将它们全部分开。您只有在准备好测试或发货时才捆绑它们。运行时与它们位于不同文件中的运行时完全相同,只是速度稍快一些,因为它只需要获取一个文件。
  • 如果是调用 bundle 命令所需的时间,我建议研究 grunt.js,它是一个可以自动执行任务的工具。您可以将项目设置为每次保存文件时捆绑。
  • @tom 哦,grunt.js 是我想要的,以便自动执行此捆绑任务。再次感谢您!

标签: javascript node.js closures anonymous-function


【解决方案1】:

browserify 允许您在客户端 js 文件中使用 require。

如果你想在构造函数中使用 p2,你还需要 game_core.js 需要 p2。

您使用 browserify 的客户端文件应如下所示

<script src="bundle.js"></script> <!-- browserify p2 game_core.js config.json --->
<script>
  var p2 = require('p2 ');
  var game_core= require('game_core.js');
  var config= require('config.json');
 /* ... */
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-09
    • 2011-05-31
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2019-05-11
    • 2012-12-31
    • 2020-08-19
    相关资源
    最近更新 更多