javascript - 在空函数中返回函数的结果是否有任何目的?

标签 javascript web google-tag-manager

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

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.

那不是代码的作用。它返回函数(它本身,实际的函数对象),而不是函数的结果。您的外部函数不是调用您的内部函数,而是创建并返回它。内部函数中的代码不会执行,直到/除非接收到外部函数返回的函数引用的代码调用它。

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>

关于javascript - 在空函数中返回函数的结果是否有任何目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32578019/

相关文章:

javascript - "Apply"RaphaelJs 中的转换

java - 支持具有相同 servlet 的两个 URI

javascript - 检查动态网页是否已完全加载的最佳方法是什么?

javascript - 如何使用nodejs驱动程序获取mongodb中的当前操作

javascript - CSS 转换不适用于 UL 列表上的最大高度切换

javascript - 如何在制定谷歌标签管理器后调用我的一些脚本?

javascript - Google 跟踪代码管理器 - 捕获选择值

javascript - alert()/datalayer.push 不同

javascript - 从该错误中可以读到什么?

javascript - 精通 Javascript 的人能简单地向我解释一下这是怎么回事吗