javascript - 这是 Closure 的正确陈述吗?

标签 javascript closures

引自 Stoyan Stefanov 的面向对象的 JavaScript(第 84 页):

enter image description here

If you're at point a, you're inside the global space. If you're at point b, which is inside the space of the function F, then you have access to the global space and to the F-space. If you're at point c, which is inside the function N, then you can access the global space, the F-space and the N-space You cannot reach from a to b, because b is invisible outside F. But you can get from c to b if you want, or from N to b. The interesting thing—the closure—happens when somehow N breaks out of F and ends up in the global space."

我认为上面的粗体句应该改为“如果你在点c,它在函数N内部,那么你可以访问全局空间和N空间”(F空间不应该被包含,因为点 c 只能访问 N 空间和全局范围 G。)。

我说的对吗?谢谢。

最佳答案

不,我认为它的意思是 N 是一个从函数 F 返回的函数,因此可以(通过闭包)访问变量 b 是在 F 中声明的。例如 ( live example ):

function F() {
    var b = 10;
    return function () {
        console.log(b);
    };      
}

var N = F(); //N is a reference to the anonymous function returned from F

N(); //logs '10' because we still have access to b (because of the closure)

关于javascript - 这是 Closure 的正确陈述吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12744105/

相关文章:

javascript - 正则表达式 - 如何匹配匹配和不匹配模式的所有字符组?

javascript - 使用 react-router 自定义动态路由

JavaScript 闭包行为异常

javascript - 通过javascript或jquery减少php中的图像文件大小

javascript - 仅当 $scope.$apply() 尚未进行时,如何调用

javascript - 更新谷歌热图

javascript - 哪个更安全 - 使用 self 还是这个?

Swift:函数与闭包的定义和语法

swift - 为什么我不能在此默认参数值中使用速记参数名称?

Swift:如何根据完成 block 中的结果重新运行函数?