Hey JavaScript experts!
I have a piece of code that looks like this:
Now I realize the inner is used in multiple places. So I shifted the inner out to same level of outer. Now inner cannot access outerVariable.
How should we handle this? Duplicating the inner in both outer and outer2 would obviously work, but not great for code reuse.
I have a piece of code that looks like this:
PHP:
function outer(){
var outerVariable = "hello world";
var inner = function(){
alert(outerVariable); // Notice how it can access outerVariable due to closure
}
call_func( inner ); // inner is given as a callback function
}
Now I realize the inner is used in multiple places. So I shifted the inner out to same level of outer. Now inner cannot access outerVariable.
PHP:
function outer(){
var outerVariable = "hello world";
call_func( inner ); // inner is given as a callback function
}
function outer2(){ // Same as outer, trying to reuse inner function.
var outerVariable = "goodbye world";
call_func( inner );
}
function inner(){
alert(outerVariable); // Fails! Cannot find outerVariable!
}
How should we handle this? Duplicating the inner in both outer and outer2 would obviously work, but not great for code reuse.
