Javascript关闭

mjm*_*che 3 javascript

以下程序返回"local",并根据教程I m reading, it is designed to demonstrate the phenomenon ofclosure`

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

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

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

var child = parentFunction();
child();
Run Code Online (Sandbox Code Playgroud)

rsp*_*rsp 6

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

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

parentFunction()();
Run Code Online (Sandbox Code Playgroud)

看到这个小提琴: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
Run Code Online (Sandbox Code Playgroud)

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

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

x = f();
Run Code Online (Sandbox Code Playgroud)

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

x = f()();
Run Code Online (Sandbox Code Playgroud)

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

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

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

2016年更新

请注意,目前这个:

function outer() {
    return function() {
        alert('inner function called');
    }
}
Run Code Online (Sandbox Code Playgroud)

可以写成:

let outer = () => () => alert('inner function called');
Run Code Online (Sandbox Code Playgroud)

使用ES6 箭头函数语法.