gpt4 book ai didi

javascript - 匿名回调函数说明

转载 作者:搜寻专家 更新时间:2023-10-31 22:57:40 25 4
gpt4 key购买 nike

我正在复习回调函数并从 http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/# 中看到以下段落

“当我们将回调函数作为参数传递给另一个函数时,我们只是传递了函数定义。我们没有执行参数中的函数。换句话说,我们没有传递带有尾随对的函数就像我们执行函数时一样执行括号 ()。

并且由于包含函数在其参数中具有回调函数作为函数定义,因此它可以随时执行回调。"

谁能解释一下?这是他们提供的两个示例。

​//The item is a callback function
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});

这是另一个例子:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
});

“请注意,回调函数不会立即执行。它会在包含函数主体内的某个指定点“回调”(因此得名)。因此,即使第一个 jQuery 示例看起来像这样:

//The anonymous function is not being executed there in the parameter. ​
​//The item is a callback function
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});

稍后将在函数体内调用匿名函数。即使没有名称,以后仍然可以通过包含函数的参数对象访问它。”

对于 jquery 的第一个例子,他们到底在说什么。如果点击#btn_1 元素,是否会执行匿名函数?我假设它会在单击按钮时执行,但这段文字中的措辞令人困惑?

同样,对于第二个示例,他们是否不需要调用作为参数传递的匿名函数?

最佳答案

在这两个示例中,您都将匿名函数作为参数传递。

$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});

jQuery 的 click 方法将一个函数作为其第一个参数。所以想象一下 click 的函数定义是这样的:

function click(fn) {
// fn will contain a reference to any
// function passed as the first parameter to click
// merely calling fn does nothing, because you are just 'calling'
// the reference.
fn;
// Since what is inside of fn is a function, you can execute it
// with the () syntax
fn();
}
// Now, you have many ways to pass a function as the first parameter to the function

// 1. As an anonymous function:
click(function() {
console.log("Hi");
});

// 2. As a named function:
click(function hello() {
console.log("Hi");
});

// 3. As a reference to a function declaration
function hiThere() {
console.log("Hi");
}
click(hiThere);

// 4. As a variable that holds an anonymous function inside
var howdy = function () {
console.log("howdy");
};
click(howdy);

想象一下,函数就像变量,但它们内部有内容,可以在最后用 () 执行。

function hi() {
console.log('bye');
}

hi; // Calls the reference, but does not execute it. This does nothing.
hi.toString(); // Returns the function as a string
hi(); // Executes the code within the function

每当你声明一个命名函数时,你都可以根据它的名字来处理它,就像你处理变量一样。当然,与变量不同的是,它们在内部保存可执行代码,而不是值。

您不能引用匿名函数,因为它是……匿名的。 UNLESS,您将它保存在有名称的东西中,例如 var

var iHoldAFunctionInside = function () {
console.log('Im not so anonymous now');
};
iHoldAFunctionInside(); // Logs "Im not so anonymous now"

这就是为什么您可以将匿名函数作为参数传递给函数,并且它可以将其作为回调执行。因为参数现在“保存”了其中的匿名函数:

function iExecuteYourCallback(callback) {
// callback contains the anonymous function passed to it
// Similar to doing:
// var callback = function () { };
callback();
}
iExecuteYourCallback(function() {
console.log('Im a callback function!');
});

希望这有助于澄清一些事情。

关于javascript - 匿名回调函数说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29933522/

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