在自执行功能中访问阴影变量 [英] Accessing Shadowed Variable in Self Executing Function

查看:110
本文介绍了在自执行功能中访问阴影变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中,是否有任何方法可以从 someFunction 中获取对 someFunction 外声明的 someValue 变量的引用,或者是否完全被相同名称的函数参数遮蔽。我很欣赏我可以将它附加到窗口并使用 this 从函数内部访问它,但是在这种情况下有没有办法访问它?



澄清。我知道参数是遮蔽变量。很明显,改变参数的名字将会消除这个问题。我的问题是在这种情况下是否有办法访问变量。
$ b $

 (函数($){

var someValue = 41;

函数someFunction(someValue){

console.log(someValue); // = 22

}

someFunction(22);


}(jQuery));


解决方案

您似乎故意隐藏变量,然后试图获得它的价值。只需给它一个不同的名字或者重命名你的参数即可。

  var someValue = 41; 
函数someFunction(myParameter){
console.log(someValue); // someValue == 41
}
someFunction(22); // logs 41


In the following example, is there any way to get a reference to the someValue variable declared outside someFunction from within someFunction or is it completely obscured by the function's parameter of the same name. I appreciate that I could attach it to window and access it from within the function using this, but is there a way of accessing it in this situation?

[Edit] To clarify. I understand that the parameter is shadowing the variable. Obviously changing the name of the parameter would remove this issue. My question is whether there is any way to access the variable given this situation.

(function($){

   var someValue = 41;

   function someFunction(someValue) {

      console.log(someValue); //= 22

   }

   someFunction(22);


}(jQuery));

解决方案

You seem to be deliberately shadowing the variable, and then trying to get its value. Just give it a different name or rename your parameter.

   var someValue = 41;
   function someFunction(myParameter) {
      console.log(someValue); // someValue == 41
   }
   someFunction(22); // logs 41

这篇关于在自执行功能中访问阴影变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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