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

后端 未结 4 638
灰色年华
灰色年华 2020-12-17 15:53

Given the following JavaScript:

var someFunction = function(id) {
  //do some stuff
  var modifyId = function(id) {
     //do some stuff
     outer.id = id;          


        
相关标签:
4条回答
  • 2020-12-17 16:08

    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.

    0 讨论(0)
  • 2020-12-17 16:15

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

    0 讨论(0)
  • 2020-12-17 16:26

    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.

    0 讨论(0)
  • 2020-12-17 16:29
    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.

    0 讨论(0)
提交回复
热议问题