Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to access an outer scope's variable once the present scope has defined one of the same name?

Tags:

javascript

It would seem not:

function o(){
  var v = 1;
  function i(){
    var v = 2;
    // any way at all, now, to access the 1 value?
  }
}

But is there?

like image 916
user3025492 Avatar asked Nov 24 '25 15:11

user3025492


1 Answers

No, within i the v symbol completely shadows the v in o, and there's no other way to get at it. With that code, there's no way for i to get at o's v.

Of course, if you used different names for the variables, that problem goes away. :-)


If instead of o you had code at global scope, you could access v as a property of the global object, because when you declare a variable globally, it becomes a property of the global object. For instance, this would work in loose mode:

var v = 1;
function i() {
    var v = 2;
    console.log("v == " + v);
    console.log("this.v == " + this.v);
}
i(); // Calling it like this makes `this` within the call the global object

Which would show

v == 2;
this.v == 1

That wouldn't work in strict mode, though, because this would be undefined within i.

On browsers, the global object has a property, window, it uses to refer to itself, so you wouldn't have to rely on this as with the above:

// Browsers only
var v = 1;
function i() {
    var v = 2;
    console.log("v == " + v);
    console.log("window.v == " + window.v);
}
i();

That works in either strict or loose mode, but only in browsers.

But global scope is a special case. For the code you quoted, no, there's no way to get there.

like image 136
T.J. Crowder Avatar answered Nov 26 '25 05:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!