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);
4
  • Tip: Use lowercase names for everything but constructor functions. Commented Aug 14, 2014 at 0:00
  • Where did you find this statement? Do you know what an "anonymous function" is? Commented Aug 14, 2014 at 0:00
  • @Bergi if I'm correct, a Anonymous function is a function with out a name. Commented Aug 14, 2014 at 0:02
  • Have you ever encountered one in code? How do you thing could this be used here? Are there examples of this in the place where you found this statement (please link it!)? Commented Aug 14, 2014 at 0:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

this will hardly ever refer to the function itself, no.
"Since Functions are objects, you can declare them literally" - huh, what?
I guess all functions are really declared literally... unless you something odd like "new Function()" which I think you can actually do...
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.