问题
In JavaScript, is it possible to specify the global context which will be used if a local variable isn't defined?
Example:
(function foo() {
console.log(bar);
})();
It will actually print window.bar
.
Can I somehow change the global context? Something like this:
var myGlobalContext = { bar: "foo" };
(function foo() {
console.log(bar);
}).applyWithGlobal(myGlobalContext);
It should print myGlobalContext.bar
.
Or attach this
to be the global context?
I hope the example is clear enough.
回答1:
The closest thing you can do is mask the global variables using a with
statement.
var myGlobalContext = {bar: "foo"};
with(myGlobalContext)
{
console.log(bar);
}
This is not the same as changing the global context, because other globals that aren't found in myGlobalContext
will still exist.
In general, the with
statement is bad, but it sounds like your use case might be one where it makes sense.
回答2:
You can do it by using .call() and referencing the variable via this.xyz
inside the function:
(function foo() {
console.log(this.bar);
}).call(myGlobalContext);
The only other way is by wrapping the function call in another scope:
(function() {
var bar = '123';
(function() {
console.log(bar);
})();
})();
回答3:
You can do something like this by passing the namespace to the IIFE:
var myNamespace = { bar: "foo" };
(function( ns ) {
console.log( ns.bar );
}( myNamespace ));
来源:https://stackoverflow.com/questions/20338445/specify-global-context-in-javascript