Is it possible in Javascript to create an external

2019-07-18 04:09发布

问题:

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?

回答1:

No, closures in JS are always lexical (i.e. referring to their parent scope).

If you want to create a closure with an explicitly set environment, you may of course use a helper function for that:

function unrelated() {
    var closure = makeClosure("hello");
    closure();
}
unrelated();

function makeClosure(a) {
    return function() { // closes only over `a` and nothing else
        console.log(a);
    }
}

That's as close a you will get to an "external closure". Notice you can only pass values to makeClosure, not references to local variables. Of course you could make objects and pass the reference to them around, and with with (not recommended!) you could even make them look like variables.