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

时间:2015-09-15 04:57:40

标签: 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运行。

1 个答案:

答案 0 :(得分:4)

  

在这个例子中,一个函数的返回作为另一个函数的返回传递。

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

  

什么时候看起来像这样

不可能,这完全不同。这会在调用以前的外部函数时立即运行代码。但是第一个例子是不运行该代码,只是创建一个函数,如果它被调用,将运行它。

这个例子可能有助于澄清它:



// 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>
&#13;
&#13;
&#13;