简体   繁体   English

JavaScript 访问内部和外部范围内同名的局部变量

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

Given the following JavaScript:给定以下 JavaScript:

var someFunction = function(id) {
  //do some stuff
  var modifyId = function(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?如何修改从内部函数范围内传递到外部函数范围的 id?

Unfortunately you can't.不幸的是你不能。 By naming the parameter in the nested function id , you've shadowed the parameter in the outer function.通过在嵌套函数id中命名参数,您已经隐藏了外部函数中的参数。 Javascript contains no facility for accessing the shadowed name. Javascript 不包含访问影子名称的工具。 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.在函数内部,没有办法(除了 Mozilla 的代码或 ES5 中的一些奇怪的东西)以任何明确的方式将范围称为上下文,也没有办法以任何直接的方式爬上词法范围链。

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.但是,是的,您应该只重命名形式参数之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么方法可以在 Javascript 中访问外部作用域中的局部作用域变量? - Any way to access local scope variable in outer scope in Javascript? Javascript外部范围变量访问 - Javascript outer scope variable access Javascript 功能 内/外/变量 Scope - Javascript Funciton Inner/Outer/Variable Scope 一旦当前范围定义了同一个名称,有没有办法访问外部范围的变量? - Is there any way to access an outer scope's variable once the present scope has defined one of the same name? 如何从 JavaScript 的外部作用域访问变量 - How to access a variable from outer scope in JavaScript Javascript范围:将外部函数中的变量传递给内部函数 - Javascript scope: passing a variable from an outer function to an inner function 在javascript中设置内部作用域的外部作用域变量 - set outer scoped variable from inner scope in javascript 在javascript中,只要名称与局部变量相同,就可以访问全局变量? - In javascript ,Access to global variable whenever its name is same with local variable? 如何使用外部 scope 中的同名变量解构 Typescript 中的变量? - How to deconstruct a variable in Typescript with a variable of the same name from an outer scope? 将参数与外部 scope 中的变量同名是不好的做法吗? - Is it bad practice to have parameters the same name as a variable in the outer scope?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM