【问题标题】:Is there any purpose to return the result of a function in an empty function?是否有任何目的在空函数中返回函数的结果?
【发布时间】:2015-09-15 04:57:39
【问题描述】:

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

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 运行。

【问题讨论】:

    标签: javascript web google-tag-manager


    【解决方案1】:

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

    那不是该代码正在做的事情。它返回的是 function(它本身,实际的函数对象),而不是函数的 result。你的外部函数不是调用你的内部函数,它是创建和返回它。内部函数中的代码不会执行,直到/除非接收到您的外部函数返回的函数引用的代码调用它。

    什么时候可以这样

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

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

    // 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 2020-03-06
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多