相关疑难解决方法(0)

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

我来自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 …
Run Code Online (Sandbox Code Playgroud)

javascript functional-programming

2
推荐指数
2
解决办法
313
查看次数

标签 统计

functional-programming ×1

javascript ×1