javascript 匿名回调函数说明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29933522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:20:01  来源:igfitidea点击:

Anonymous Callback Function Clarification

javascriptnode.jsfunctioncallback

提问by djfkdjfkd39939

I'm brushing up on callback functions and came across the following passage from http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/#

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

"When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren't passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.

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

And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime."

并且由于包含函数在其参数中将回调函数作为函数定义,它可以随时执行回调。”

Can someone explain that? Here are two examples they provided.

有人可以解释一下吗?这是他们提供的两个示例。

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

Here is another example:

这是另一个例子:

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

"Note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function's body. So, even though the first jQuery example looked like this:

“请注意,回调函数不会立即执行。它在包含函数体内的某个指定点被“回调”(因此得名)。因此,即使第一个 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");
   });

the anonymous function will be called later inside the function body. Even without a name, it can still be accessed later via the arguments object by the containing function."

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

For the first example with jquery, what are they saying exactly. If the #btn_1 element is clicked, will the anonymous function be executed? I am assuming it will be executed if the button is clicked, but the wording from the passage was confusing?

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

Similarly, for the second example, do they not need to call the function that they passed as an argument bc its anonymous?

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

回答by

In both examples, you are passing an anonymous function as a parameter.

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

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

jQuery's click method takes a function as its first parameter. So imagine that click's function definition is this:

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);

Just imagine that functions are like variables, but they have content inside that can be executed with ()at the end.

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

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

Whenever you declare a named function, you can do stuff with it according to its name, like you would do with variables. Of course, unlike variables, they hold executable code inside, and not values.

每当您声明一个命名函数时,您都可以根据其名称对其进行操作,就像您对变量所做的那样。当然,与变量不同的是,它们在内部保存可执行代码,而不是值。

You can't reference an anonymous function, because it's well... anonymous. UNLESS, you hold it inside of something that has a name, like a var.

你不能引用匿名函数,因为它很好......匿名。除非,你把它放在有名字的东西里面,比如var.

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

And that is why you can pass an anonymous function as a parameter to a function, and it can execute it as a callback. Because the parameter now 'holds' the anonymous function inside of it:

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

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!');
});

Hope this helps clear things a bit.

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

回答by Arun P Johny

In javascript functions are first class members to you can pass a function as an parameter and the called function can accept it as a named argument.

在 javascript 函数中,函数是第一类成员,您可以将函数作为参数传递,被调用的函数可以将其作为命名参数接受。

A simple example can be as below

一个简单的例子可以如下

function testme(callback) {
    //here the argument callback refers to the passed function

    //the timer is used just to delay the execution of the callback
    setTimeout(function () {
        //the passed function is called here
        callback();
    }, 1000)
}

testme(function () {
    alert('x')
})

Demo: Fiddle

演示:小提琴



In your examples, yes the first callback will be executed once the element with id btn_1is clicked.

在您的示例中,是的,一旦btn_1单击具有 id 的元素,就会执行第一个回调。