Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 222
Raj Avatar asked Feb 21 '23 19:02

Raj


1 Answers

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.

like image 96
jAndy Avatar answered Mar 15 '23 22:03

jAndy