var str = 'internet';
performAction(function(str) {
console.log(str);
});
Is there a problem with having a private variable str
and also having a callback function with a parameter of the same name?
Thanks!
var str = 'internet';
performAction(function(str) {
console.log(str);
});
Is there a problem with having a private variable str
and also having a callback function with a parameter of the same name?
Thanks!
Share Improve this question edited Dec 10, 2011 at 12:22 James Hill 61.8k22 gold badges149 silver badges166 bronze badges asked Dec 10, 2011 at 1:10 Filo StacksFilo Stacks 2,0412 gold badges21 silver badges21 bronze badges 1- 1 No - just don't forget that it's not actually the same variable. – Sam Dufel Commented Dec 10, 2011 at 1:14
2 Answers
Reset to default 11This is just a standard scope situation - the fact that it is an anonymous function expression passed as a parameter to another function doesn't matter. Note that within your performAction()
function (which you don't show) it will not have any access to the str
that is the parameter of the callback function - if performAction()
references str
it will get the global "internet" variable (or its own local str
if defined).
A function's parameters are, for scope purposes, the same as that function's local variables, which means they mask other variables of the same name from outer scope - but variables with different names can still be accessed even if defined in a wider scope.
Where it could get confusing is if you do something like this:
var str = "internet";
(function(str) {
console.log(str); // "internet"
str = "local param";
console.log(str); // "local param"
})(str);
console.log(str); // "internet"
In that case I have a function with a parameter called str
but when I call it I'm passing in a different str
. Note that changing str
within that function only changes the local str
, not the global one. They are two different variables...
There is technically no problem with it. The function will log the str
that is currently in scope (your parameter).
For obvious reasons, this is not considered a good idea. At the very least, it makes for unreadable code.