开发者

JavaScript Access Local Variable with Same Name in Inner and Outer Scope

Given the following JavaScript:

var someFunction = function(id) {
  //do some stuff
  var modifyId = func开发者_StackOverflowtion(id) {
     //do some stuff
     outer.id = id; //is there any way to modify the id variable in the outer scope from here?
  }
}

How do you modify the id passed into the outer function scope from within the inner function scope?


Unfortunately you can't. By naming the parameter in the nested function id, you've shadowed the parameter in the outer function. Javascript contains no facility for accessing the shadowed name. The only option is to choose a different name for one of the variables.


No, there isn't. From within a function, there's no way (something weird in Mozilla's code or ES5 aside) to refer to the scope as a context in any explicit way, and there's no way to climb up the lexical scope chain in any direct way.

Good question though.


var someFunction = function(id) {
  //do some stuff
  var oid = id;
  var modifyId = function(id) {
     //do some stuff
     // you can access the outer id via the oid variable
  }
}

But, yes, you should just rename one of the formal parameters.


Why can't you just rename one of the variables?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜