10

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?

AlexStack
  • 16,766
  • 21
  • 72
  • 104

3 Answers3

15

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);      
});
Túbal Martín
  • 709
  • 6
  • 6
  • so what if you actually want the global object as in you want your module to run an other contexts? – gman May 27 '15 at 20:19
  • If I understand you correctly @gman...say our code is inside an iframe but we need the top global object. We can do this: `// Code inside iframe define(['window'], function(win) { var topWin = win.top; // Manipulate iframe's window properties win.foo = 1; console.log(win.foo); // Manipulate top window properties topWin.foo = 2; console.log(topWin.foo); });` – Túbal Martín Jun 08 '15 at 18:36
  • sorry, I meant I'm not running in the browser so the global object is not `window` – gman Jun 09 '15 at 03:02
  • Thx4this, as 2fast AMDize naive globals from pre-{AMD&equiv} code(til complete fix(hard)), of the 3 solutions here I suspect this 1 notably the best, as it defines&uses a global MODULE to hold the naive globals, notably a AMD https://en.wikipedia.org/wiki/Singleton_pattern for ‘window’, so that {also allows other even simul global spaces to be plugged in, incl regularly w/o editing module} + {esp as singletons r what’s used for POST-AMD design of globals (per all 4 rated-0+ solutions of http://stackoverflow.com/q/5608685 )},so I try it 1st 2now quick AMDize lots old code&if works well,+1 here! – Destiny Architect Jun 02 '16 at 04:22
  • @gman Have it return [`self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) instead of window. – jpaugh Apr 16 '18 at 19:56
5

If you're not in strict mode, you can do this:

(function() {
  var global = this;

  define(function(){
    global.x = ...
    global.y = ...
  });
})();

The outer anonymous function that we immediately invoke is invoked with no particular special this value, and so (since this isn't in strict mode), receives the global object as this. (In strict mode, it would receive undefined instead.) So we grab this into a variable (global) within the anonymous function, and use it from the function you pass into define (which closes over it).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • this is a good idea, but I'm still wondering if there is a mechanism from inside the `define()` function that doesn't require embedding my code in an immediate call function? – AlexStack Mar 16 '13 at 10:43
5

A variation on @TJCrowder's answer, which also works in strict mode:

(function(global) {
    define(function() {

        global.a="this";
        global.b="that";

    });
})(this);

By calling the immediately invoked function with the argument 'this' (which outside a function is the global scope), then whatever the global scope is it gets passed into the IIF as the argument 'global'.

This also avoids hard-coding to the 'window' object, an advantage since that doesn't apply in non-browser environments.

harmic
  • 28,606
  • 5
  • 67
  • 91
  • If I put that code in a file and pass it to Node, `this` is `{}`, whether or not I am in strict mode. – Louis May 06 '15 at 10:22
  • @Louis I believe [`self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) would work in Node, and it certainly works in the browser. – jpaugh Apr 16 '18 at 19:55