繁体   English   中英

Javascript关闭

[英]Javascript closure

以下程序返回“本地”,根据我m reading, it is designed to demonstrate the phenomenon of的教程m reading, it is designed to demonstrate the phenomenon of关闭m reading, it is designed to demonstrate the phenomenon of

我不明白为什么,最后,为了调用父函数,它将它分配给变量“child”然后调用“child”。

为什么它只是编写parentFunction(); 在末尾?

var variable = "top-level";
function parentFunction() {
  var variable = "local";
  function childFunction() {
    print(variable);
  }
  return childFunction;
}

var child = parentFunction();
child();

parentFunction()返回另一个赋给var child的函数。 然后,调用child()来调用对parentFunction()的调用返回的函数。

只运行parentFunction(); 最后不会做任何有用的事情,因为你只会丢弃它的返回值,这是一个函数。 但这会奏效:

parentFunction()();

看到这个小提琴: http//jsfiddle.net/USCjn/

更新:一个更简单的例子:

function outer() { // outer function returns a function
    return function() {
        alert('inner function called');
    }
}

x = outer(); // what is now in x? the inner function

// this is the same as saying:
//    x = function() {
//        alert('inner function called');
//    }

x(); // now the inner function is called

看到这个小提琴: http//jsfiddle.net/bBqPY/

JavaScript中的函数可以返回函数(可以返回函数(可以返回函数......))。 如果你有一个返回另一个函数的函数,那么这意味着当你调用外部函数时,你得到的是内部函数,但它还没有被调用。 你必须调用你所获得的值作为实际运行内部函数体的函数。 所以:

x = f();

表示 - 运行函数f并在x中存储它返回的内容(可以是字符串,数字,对象,数组或函数)。 但是这个:

x = f()();

表示 - 运行函数f,期望它返回一个函数并运行返回的函数(第二个括号)并在x中存储返回的函数返回的内容。

这里的函数f是一个高阶函数,因为它返回另一个函数。 函数也可以将另一个函数作为参数。 一般来说函数式编程语言最强大的思想之一就是JavaScript,特别是函数只是普通的值,比如可以返回和传递的数组或数字。

您必须首先掌握高阶函数的概念,以理解JavaScript中的闭包和事件系统。

2016年更新

请注意,目前这个:

function outer() {
    return function() {
        alert('inner function called');
    }
}

可以写成:

let outer = () => () => alert('inner function called');

使用ES6 箭头函数语法

关于闭包的惊人部分是内部函数(在本例中为childFunction )可以引用其作用域之外的变量(在本例中为变量 )。 parentFunction不返回childFunction的结果,但实际的参考作用!

这意味着当您执行以下操作时......

var child = parentFunction();

...现在, child具有对childFunction的引用,并且childFunction仍然可以访问创建函数时所具有的任何变量,即使它们不再存在。

为了让parentFunction调用childFunction,您需要更改代码,如下所示:

从...

return childFunction;

至:

return childFunction();

道格拉斯克罗克福德(JSON的先驱,除其他外)有一篇专门讨论闭包和javascript范围的文章,看看他关于javascript的其他文章是值得的。

正在证明的一点是,返回并分配给child parentFunction的函数仍然引用 parentFunction 声明的variable ,而不是在调用child()之外声明的variable

在javascript中创建变量作用域的唯一方法是在函数体中。 通常情况下, variable里面parentFunction会被丢弃该函数返回后。

但是,因为你宣布里面的功能parentFunction所引用variable在该范围内,并通过它的parentFunction ,该variableparentFunction通过新功能的提法保留。

这保护variable不受外部操作的影响,除了在parentFunction内围绕它关闭的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM