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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With