[英]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.