javascriptscoperequirejsglobal-variablesrequirejs-define

How do I get global scope inside define function?


Can you get global scope while using strict mode and also making sure that you can run on non window environment.

See these examples:

define(['other', 'thing'], function() {
    // this === window in desktop environment
    // this === GLOBAL in node environment
});
define(['other', 'thing'], function() {
    "use strict";
    // this === undefined in desktop environment
    // this === GLOBAL in node environment
    // As of my understanding node has to be configured using `node --use_strict`
    // (http://stackoverflow.com/questions/9031888/any-way-to-force-strict-mode-in-node)
    // But that not the point.
});

Is there any way to get the global variable (window/GLOBAL) inside define.


Solution

  • var global = Function("return this")();
    

    If you don't have access to Function, then also try

    var Function = function(){}.constructor,
        global = Function("return this")();