return 空函数中函数的结果有什么用吗?

Is there any purpose to return the result of a function in an empty function?

在此示例中,一个函数的 return 作为另一个函数的 return 传递。我不确定我是否理解这样做的必要性。 示例:

function(){
    return function(){
        // Check if the page contains the div
        var node = document.getElementById("sponsored-content"); // use whatever id your block has
        isInBody = document.body.contains(node);

        // If true
        if (isInBody){
            dataLayer.push({'event':'spContent-detected'});
        }
    }
}

什么时候可以变成这样:

 function(){
        // Check if the page contains the div
        var node = document.getElementById("sponsored-content"); // use whatever id your block has
        isInBody = document.body.contains(node);

        // If true
        if (isInBody){
            dataLayer.push({'event':'spContent-detected'});
        }
    }

为了获得更好的上下文,tag manager guide 是那段原始代码的来源。如果条件为假,添加它似乎会停止任何其他 js 到 运行。

In this example, the return of one function is passed as the return of another function.

那不是代码的作用。它返回 function(它本身,实际的函数对象),而不是函数的 result。您的外部函数不是调用您的内部函数,而是创建和返回它。内部函数中的代码未执行 until/unless 代码接收函数引用你的外部函数 returns 调用它。

When it could look like this

它不能,它做了完全不同的事情。那立即 运行 是调用以前的外部函数时的代码。但是第一个示例不是 运行 编写该代码,只是创建一个函数,如果它被调用,将 运行 它。

这个例子可能有助于阐明它:

// A function that creates functions, in this case functions that multiply
// whatever number you give them by the value used when creating the function
function makeMultiplier(mult) {
  return function(arg) {
    return arg * mult;
  };
}

// Make (but don't run!) a function that multiplies by 10
var m1 = makeMultiplier(10);

// Run it a couple of times
snippet.log(m1(5)); // 50
snippet.log(m1(7)); // 70

// Make (but don't run!) a function that multiplies by 7
var m2 = makeMultiplier(7);

// Run it a couple of times
snippet.log(m2(5)); // 35
snippet.log(m2(7)); // 49

// Run each of them again, just to show that they aren't inter-related
snippet.log(m1(6)); // 60
snippet.log(m2(6)); // 42
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>