为什么Javascript函数在实例化时的行为与执行不同?

Edw*_*uay 2 javascript functional-programming

我来自C#/ PHP并试图了解Javascript的想法,即函数是变量/对象,并且具有准构造函数等.

任何人都可以解释为什么以下代码的功能,即:

  1. 为什么在实例化变量/函数时不显示"2" test
  2. 执行变量/功能时为什么不显示"1" test

码:

var setup = function () {
    console.log(1);
    return function() {
        console.log(2);
    };
};

var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2
Run Code Online (Sandbox Code Playgroud)

添加:

谢谢@thejh @Justin所以函数返回一个完全不同的函数,与第一个函数无关(我想第二个函数作为第一个函数的构造函数),如果我将它注释掉,那就更清楚了:

$(document).ready(function() {

    var setup = function () {
        console.log(1);
//        return function() {
//            console.log(2);
//        };
    };

    var test = setup(); // 1
    test(); // "test is not a function"
    test(); // "test is not a function"
    test(); // "test is not a function"

});
Run Code Online (Sandbox Code Playgroud)

Nic*_*ver 5

因为你在创建它时会返回一个不同的函数(在return你的第一行中没有调用的那个)... 就是在其他调用上执行的函数.例如,这会给你1那么2:

var test = setup()(); // 1, 2
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试一下.


Jus*_*ner 5

你只是setup()第一次打电话.调用后,它返回的新函数将被分配给test.从那以后,你称之为新功能:

// calls setup which logs 1 and returns a new function.
// setup also returns a new function and assigns that new function to test.
var test = setup(); 

// test now is the equivalent of var test = function(){ console.log(2); };

// call the new function that setup returned which logs 2
test();

// and again
test();

// and again
test();
Run Code Online (Sandbox Code Playgroud)