Skip to content Skip to sidebar Skip to footer

Specify Global Context In Javascript

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 ac

Solution 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.

Solution 2:

You can do it by using .call() and referencing the variable via this.xyz inside the function:

(functionfoo() {
    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);
    })();
})();

Solution 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 ));

Post a Comment for "Specify Global Context In Javascript"