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

时间:2010-12-16 15:38:28

标签: javascript functional-programming

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

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

  1. 实例化变量/函数test
  2. 时,为什么不显示“2”
  3. 执行变量/函数test
  4. 时,为什么不显示“1”

    代码:

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

    加入:

    感谢@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"
    
    });
    

6 个答案:

答案 0 :(得分:5)

因为你从创建它时调用的函数返回不同的函数(return中的那个,你没有在第一行调用的那个)... 是在其他调用上执行的内容。例如,这会为您提供1,然后2

var test = setup()(); // 1, 2

You can test it here

答案 1 :(得分: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();

答案 2 :(得分:1)

在第一次对setup()进行测试时,你正在执行整个函数,因此运行console.log(1),然后返回一个新函数。

现在,您将第一个函数的返回值指定为运行console.log(2)的下一个函数,所以现在测试返回函数的引用。

您的后续调用只运行运行console.log(2)

的函数

答案 3 :(得分:1)

调用setup()打印1并返回对该匿名函数的引用。打电话打印2

答案 4 :(得分:1)

想象一下,而不是

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

此等效OOP syntax

var setup = new Function("\
    console.log(1);\
    return new Function(\"\
        console.log(2);\
    \");\
");
var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2

我认为你现在应该对此更加熟悉。

答案 5 :(得分:1)

您执行setup()时执行以下两行:

console.log(1);
function() { console.log(2); }
  • 第一行日志“1”
  • 第二行没有记录任何东西,因为函数没有被调用,它只创建一个对象(这个对象就是一个函数)。

当你执行test()时,你实际上调用了你创建的函数,因此你记录了“2”

JS是一种函数式语言,你必须看到像第一个公民对象这样的函数。