gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:59:09 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com