[英]Why is a function not defined at certain points in my script when I am requiring the function at the top?
I am making a game using Javascript.我正在使用 Javascript 制作游戏。 I use webpack to bundle my modules, so at the end of each Javascript file I use
module.exports
.我使用 webpack 来捆绑我的模块,所以在每个 Javascript 文件的末尾我使用
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
}
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(…)
在上面的每个调试点,如果我打开 Chrome 开发工具并输入
Spaceship
我会得到Uncaught ReferenceError: Spaceship is not defined(…)
If I change function randomSpaceship
as follows:如果我改变函数
randomSpaceship
如下:
Game.prototype.randomSpaceship = function() {
//DEBUGGER 3
var s = new Spaceship();
}
Then at DEBUGGER 3, Spaceship
is now defined (if I open dev tools I get that Spaceship is a function).然后在调试器 3 中,现在定义了
Spaceship
(如果我打开开发工具,我会发现 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.js 的顶部声明并分配了变量 Spaceship。
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.发生这种情况是因为您没有在
Game
和add_spaceships
函数中使用Spaceship
变量,调试点位于add_spaceships
DEBUGGER 1
和add_spaceships
DEBUGGER 2
调试点,因此 Chrome 不会在闭包中捕获此变量。 In DEBUGGER 3
you use the variable and so it's captured in a closure and you can inspect it.在
DEBUGGER 3
您使用变量,因此它被捕获在一个闭包中,您可以检查它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.