accessing global object when using requirejs

AlexStack picture AlexStack · Mar 16, 2013 · Viewed 10.3k times · Source

I know it's not recommended to use the global object and the whole idea behind using AMD is to avoid using the global object. But for some legacy code, I have to define some stuff in the global object. Currently the code looks like this:

//example2.js
define(function(){
  var globalObject = window;
  globalObject.x = ...
  globalObject.y = ...
});

It works but hard coding the global object window doesn't look very nice and I'm curious to see if it is possible to remove it. When define() was not used, the code looked like this:

//example1.js
x = ...
y = ...

I know, I know you hate this code, but let's be to the point: how can the global variable be accessed in a structured manner inside the define() function in requirejs? I wish there was something like a hidden last parameter to the function that is passed to the define() like this:

//example3.js
define(function(globalObject){
  globalObject.x = ...
  globalObject.y = ...
});

Or even simpler: the this variable would point to the global object inside that function. For example:

//example4.js
define(function(){
  this.x = ...
  this.y = ...
});

Note: I'm not sure about this last one. Investigating the this variable inside the function that is passed to require() says that it is equal to window which can be the answer to my question, but I haven't been able to find any documentation that mentions the context that the passed function is running. Maybe it is running in the context of the global variable after all?

Answer

Túbal Martín picture Túbal Martín · Sep 16, 2014

I suggest you to create a module that returns the window object. This is specially useful for unit testing purposes (mocking dependencies).

window.js

define(function(){
   return window;
});

app.js

define(['window'], function(win) {
  // Manipulate window properties
  win.foo = 1;  
  console.log(win.foo);      
});