var global = Function("return this")();
If you don't have access to Function
, then also try
var Function = function(){}.constructor,
global = Function("return this")();
Frage
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
.
Lösung
var global = Function("return this")();
If you don't have access to Function
, then also try
var Function = function(){}.constructor,
global = Function("return this")();
Andere Tipps
This may or may not help, but I did come up with a way to override the context of requirejs modules using the following code...
require.s.contexts._.execCb = function(name, callback, args) {
return callback.apply(/* your context here */, args);
};
Again, not sure if that'll help with use strict
and all, but who knows... :)
What i have come op with so far:
(function(root) { // Here root refers to global scope
define('mything', ['other', 'thing'], function() {
});
}(this);
But then I can't use r.js
to minify my application.
And another could be to check what to use:
define(['other', 'thing'], function() {
var root = typeof GLOBAL != 'undefined' ? GLOBAL : window;
});
Yet another way it to define a global file which returns the global:
global.js:
define(function() {
return typeof GLOBAL != 'undefined' ? GLOBAL : window;
});
mything.js
define(['global', 'other', 'thing'], function(root) {
// root === window/GLOBAL
});
But I don't like these way because what if some 3. global variable is introduced this will break, or if the user in a browser environment defines GLOBAL
then that will be returned.
I would like to see if anyone have come up with a smarter way.
What if you stored the window reference on another universally accessible object, such as Object.prototype or something along those lines?
This is what I usually do (it works for browsers, node.js and RingoJS - even in strict mode):
if (!global) var global = this;
define(['other', 'thing'], function() {
// use global
});
define(['other', 'thing'], function() {
"use strict";
// use global
});
Read the following StackOverflow thread for more details: Defining an implementation independent version of the global object in JavaScript