在Javascript中是否有可能创建一个外部闭包? [英] Is it possible in Javascript to create an external closure?

查看:116
本文介绍了在Javascript中是否有可能创建一个外部闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,要创建一个闭包,您需要在另一个函数中创建它,并获取其父对象的范围:

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?

推荐答案

词法(即引用它们的父范围)。

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

如果你想创建一个带有显式设置环境的闭包,你当然可以使用一个帮助函数: / p>

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);
    }
}

关闭。注意,你只能将值传递给 makeClosure ,而不是引用局部变量。当然,你可以创建对象,并将引用传递给他们,并且 (不推荐!)你甚至可以让他们看起来像变量。

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.

这篇关于在Javascript中是否有可能创建一个外部闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆