Raj
Raj

Reputation: 3061

How to reference a global scope variable into the local scope?

var b=1;

function someFunc(b) {
     //here 
}

I want to be able to reference the variable b that is defined outside the function. How can this be done in javascript?

Upvotes: 4

Views: 879

Answers (1)

jAndy
jAndy

Reputation: 236032

You need to access it via the global object, which is window in a browser and global in node.js for instance.

var b=1;

function someFunc(b) {
    alert( window.b ); // or console.log( global.b );
}

Why ? Well, the such called Activation Object (in ES3) or the Lexical Environment Record (ES5) will overlap the variable name b. So anytime a JS engine resolves b it'll stop at the first occurence, which is in its own Scope.

Upvotes: 8

Related Questions