Defining an implementation independent version of the global object in JavaScript
Posted
by
Aadit M Shah
on Stack Overflow
See other posts from Stack Overflow
or by Aadit M Shah
Published on 2011-11-26T17:14:43Z
Indexed on
2011/11/26
17:52 UTC
Read the original article
Hit count: 319
I'm trying to define the global
object in JavaScript in a single line as follows:
var global = this.global || this;
The above statement is in the global scope. Hence in browsers the this
pointer is an alias for the window
object. Assuming that it's the first line of JavaScript to be executed in the context of the current web page, the value of global
will always be the same as that of the this
pointer or the window
object.
In CommonJS implementations, such as RingoJS and node.js the this
pointer points to the current ModuleScope
. However, we can access the global
object through the property global
defined on the ModuleScope
. Hence we can access it via the this.global
property.
Hence this code snippet works in all browsers and in at least RingoJS and node.js, but I have not tested other CommomJS implementations. Thus I would like to know if this code will not yield correct results when run on any other CommonJS implementation, and if so how I may fix it.
Eventually, I intend to use it in a lambda expression for my implementation independent JavaScript framework as follows (idea from jQuery):
(function (global) {
// javascript framework
})(this.global || this);
© Stack Overflow or respective owner