简体   繁体   中英

Using both anonymous functions and functions stored in variables as callback arguments JavaScript

I'm not completely clear what this is supposed to mean. I guess my question is if someone could clear this up for me. What I know from Callbacks so far:

function Hello(Callback,a,b){
Callback(a,b);
}

function Hi(a,b){
alert("Hi " + a + b);
}

Hello(Hi,5,6);

In JavaScript, Functions are Objects just like Strings and Numbers, because of that feature you are able to pass Functions as variables into other Functions.

function Hello(Callback,a,b){
Callback(a,b);
}

function Hi(a,b){
alert("Hi " + a + b);
}

Hello(Hi,5,6);

In your snippet, you declare a function called Hello that takes three arguments. The Hello Function will then "call Callback as a Function", actually executing the Hi function that was passed in given your last line of code.

You have to be careful about using Functions like, especially with "this". Since "this" refers to the self-containing object, "this" will actually refer to the Function in certain contexts.

However, that is not what an Anonymous Function is. A modified version of your example:

function Hello(Callback, a, b){
   Callback(a,b);
}
Hello(function(a,b){
  alert("Hi " + a + b);
}, 5, 6);

That function that get's passed in is Anonymous, it isn't named (the JavaScript engine will give it a unique name, but it won't look pretty).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM