问题描述
我正在使用 Javascript 制作游戏.我使用 webpack 来捆绑我的模块,所以在每个 Javascript 文件的末尾我使用 module.exports
.下面是一个例子:
I am making a game using Javascript. I use webpack to bundle my modules, so at the end of each Javascript file I use module.exports
. Here is an example:
//spaceship.js
var Spaceship = function(options) {
this.position = options.position
this.name = options.name
}
module.exports = Spaceship
//game.js
var Spaceship = require("./spaceship");
var Game = function() {
this.num_spaceships = 5;
this.spaceships = [];
// DEBUGGER 1
this.add_spaceships();
}
Game.prototype.add_spaceships = function() {
// DEBUGGER 2
for(var i = 0; i < this.num_spaceships; i++) {
this.spaceships.push(this.randomSpaceship
}
}
Game.prototype.randomSpaceship = function() {
//DEBUGGER 3
}
在上面的每个调试点,如果我打开 Chrome 开发工具并输入 Spaceship
我得到 Uncaught ReferenceError: Spaceship is not defined(...)
At each of the debugging points above, if I open Chrome dev tools and type in Spaceship
I get Uncaught ReferenceError: Spaceship is not defined(…)
如果我改变函数 randomSpaceship
如下:
If I change function randomSpaceship
as follows:
Game.prototype.randomSpaceship = function() {
//DEBUGGER 3
var s = new Spaceship();
}
然后在 DEBUGGER 3 中,Spaceship
现已定义(如果我打开开发工具,我会发现 Spaceship 是一个函数).
Then at DEBUGGER 3, Spaceship
is now defined (if I open dev tools I get that Spaceship is a function).
为什么会这样?我想它可能与变量提升有关,但我在文件 game.js 的顶部声明并分配了变量 Spaceship.
Why does this happen? I imagined it could have something to do with variable hoisting perhaps, but I am declaring and assigning the variable Spaceship at the top of the file game.js.
推荐答案
发生这种情况是因为您没有在 Game
和 add_spaceships
中使用 Spaceship
变量code> 函数位于 DEBUGGER 1
和 DEBUGGER 2
调试点所在的位置,因此 Chrome 不会在闭包中捕获此变量.在 DEBUGGER 3
中,你使用了变量,所以它被捕获在一个闭包中,你可以检查它.
This happens because you don't use Spaceship
variable inside Game
and add_spaceships
functions where DEBUGGER 1
and DEBUGGER 2
debugging points are located and so Chrome doesn't capture this variable in closure. In DEBUGGER 3
you use the variable and so it's captured in a closure and you can inspect it.
这篇关于当我需要顶部的函数时,为什么我的脚本中的某些点没有定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!