Why is a function not defined at specific points in my script when I need a function on top?

I am making a game using Javascript. I use webpack to build my modules, so at the end of every 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
}

At each of the debug points above, if I open the Chrome dev tools and type Spaceship, I getUncaught ReferenceError: Spaceship is not defined(…)

If I change the function randomSpaceshipas follows:

Game.prototype.randomSpaceship = function() {
  //DEBUGGER 3
  var s = new Spaceship();
}

Then in DEBUGGER 3 it is now defined Spaceship(if I open the dev tools, I get that Spaceship is a function).

Why is this happening? I suggested that this could be due to a variable lift, perhaps, but I declare and assign a Spaceship variable at the top of the game.js.

+2
1

, Spaceship Game add_spaceships , DEBUGGER 1 DEBUGGER 2, Chrome . DEBUGGER 3 , , , .

+2

Source: https://habr.com/ru/post/1661794/


All Articles