1

I'm learning client-side javascript and i noticed in some tutorials let's say we are making a game, even with webpack bundler in place, they still do:

// game.js
function Game() {
  // ... some code
}

module.exports = Game;

// index.js

const Game = require("./game.js");
window.Game = Game;

What's the point of adding such constructor function to window? we can always require them wherever we use it and use webpack to bundle them right?

smilence
  • 349
  • 4
  • 9
  • Attaching properties to window object is not a good approach. Consider not to listen those tutors who suggest to do like this. – uamanager Jun 20 '20 at 23:56
  • @uamanager thx, do you have suggestion on avoiding circular dependency without it? – smilence Jun 21 '20 at 04:54

1 Answers1

1

Tutorials do that, because ES6 module scripts have an own ("closed") scope of variables, which doesn't allow to play around with its objects outside of it. See question ES6 module scope for more about this topic.

With window.Game = Game; the Game instance becomes accessible everywhere, which can ne good for debugging over the browser console, but you shoudn't do this in a deployed software build.

Niklas E.
  • 1,848
  • 4
  • 13
  • 25
  • thx. i went further on the project and realized they did this because otherwise it's very easy to have a circular dependency when A requires B, B requires C, while C just need a constant from A. i'll dig a bit how we usually solve that in production – smilence Jun 21 '20 at 04:53