0

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);
Peter O.
  • 32,158
  • 14
  • 82
  • 96

1 Answers1

1

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

Charles Smartt
  • 349
  • 2
  • 8
  • `this` will hardly ever refer to the function itself, no. – Bergi Aug 14 '14 at 00:13
  • "*Since Functions are objects, you can declare them literally*" - huh, what? – Bergi Aug 14 '14 at 00:14
  • I guess all functions are really declared literally... unless you something odd like "new Function()" which I think you can actually do... – Charles Smartt Aug 14 '14 at 00:21
  • Technically, only function declarations are *declared*, what you mean is that function *expressions* can take the place of every arbitrary expression in the code. I've never heard/used the term "function literal", though it [seeems to exist](http://stackoverflow.com/q/5857459/1048572) – Bergi Aug 14 '14 at 14:52