问题
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));
回答1:
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
回答2:
There is no way to log the someValue
that was declared outside the function, unless you're going to pass the variable:
(function($){
var someValue = 41;
function someFunction(someValue, otherValue) {
console.log(someValue, otherValue); //= 22 41
}
someFunction(22, someValue);
}(jQuery));
Or rename the parameter:
(function($){
var someValue = 41;
function someFunction(otherValue) {
console.log(someValue); //= 41
}
someFunction(someValue);
}(jQuery));
This is because the someValue
name you use as parameter overshadows the one declared outside the function.
回答3:
Because you are using local variable (var), the context of someValue is set to the function. The best solution is to use a different name as suggested by others, if you are desperate to use the same name though you could attach it to window object by removing the var keyword like so:
(function($) {
someValue = 41;
function someFunction(someValue) {
console.log(window.someValue); //= 41
console.log(someValue); //= 22
}
someFunction(22);
}(jQuery));
来源:https://stackoverflow.com/questions/13761271/accessing-shadowed-variable-in-self-executing-function