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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This 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 thestrthat is the parameter of the callback function – ifperformAction()referencesstrit will get the global “internet” variable (or its own localstrif 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:
In that case I have a function with a parameter called
strbut when I call it I’m passing in a differentstr. Note that changingstrwithin that function only changes the localstr, not the global one. They are two different variables…