简体   繁体   English

当方法具有相同名称的参数时访问闭包变量

[英]Accessing a closure variable when the method has an argument with the same name

Consider the following code: 考虑以下代码:

function() {
  var a = "Hello World";

  function foo(a) {
    alert(a);
  }
}

This will print the value passed to foo . 这将打印传递给foo的值。

How can I access the a variable defined in the closure so that "Hello World" will be printed? 如何访问闭包中定义a变量,以便打印“ Hello World”?

You can't because it gets overridden in the functions scope. 您不能因为它在函数作用域中被覆盖。 I also don't understand why such a construct would be useful. 我也不明白为什么这样的构造会有用。 It's very confusing to say the least. 至少可以说这非常令人困惑。 Just change the argument or variable name. 只需更改参数或变量名。

If you don't use var when declaring a variable, it will be global and you can access it via window.a . 如果在声明变量时不使用var ,它将是全局的,您可以通过window.a访问它。 This also work if the outer function is bound to the window object. 如果外部函数绑定到窗口对象,这也将起作用。

By the way, if you have control over variable and parameter names, you better name them in a better and less confusing way 顺便说一句,如果您可以控制变量名和参数名,则最好以一种更好且更容易混淆的方式来命名它们

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM