JavaScript 访问内部和外部范围内同名的局部变量 [英] JavaScript Access Local Variable with Same Name in Inner and Outer Scope

查看:27
本文介绍了JavaScript 访问内部和外部范围内同名的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 JavaScript:

Given the following 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?
  }
}

如何在内部函数作用域内修改传入外部函数作用域的id?

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

推荐答案

不幸的是你不能.通过在嵌套函数 id 中命名参数,您隐藏了外部函数中的参数.Javascript 不包含用于访问隐藏名称的工具.唯一的选择是为其中一个变量选择不同的名称.

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.

这篇关于JavaScript 访问内部和外部范围内同名的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆