Normally, to create a closure, you create it inside another function, and it gets the scope of its parent:
var parent = function(){
var a = "works!";
var subfunction(){
console.log(a); // "works!"
}
subfunction();
}
I'm trying to figure out a way to emulate this closure behavior with a function that is defined outside of the parent function. I know this is possible using parameters:
var parent = function(){
var a = "hello";
subfunction(a);
}
var subfunction(a){
console.log(a); // works, but because it's a param
}
I'm trying to figure out if there's a way to do it without having to explicitly set all parameters. I was initially thinking I'd be able to pass the functions local scope object as a parameter
var parent = function(){
var a = "hello";
subfunction(localScope);
}
var subfunction(localScope){
console.log(localScope.a); // not going to work this way
}
... but I've since discovered that it's impossible to get a reference to a function's scope. Is there some other way to emulate a closure outside of the actual scope of a function?