2

I'm trying to understand why its necessary to pass a function as an argument in order to be utilized as a callback function. What is the difference if I simply call the function directly within the parent function.

http://jsfiddle.net/7Lsafchu/5/

function main(statement, callback) {
    $("body").append("Statement: " + statement + "\n");
    callback();    
}

function anyFunction() {
        $("body").append("<p>I'm writing to a wall</p>");
}

main("This is test 1",anyFunction);


function main2(statement, callback) {
    $("body").append("Statement: " + statement);
    anyFunction2();    
}

function anyFunction2() {
        $("body").append("<p>I'm writing to a wall Again</p>");
}

main2("This is test 2");
RustyShackleford
  • 25,262
  • 6
  • 22
  • 38
  • 7
    There's no difference; one reference to a function is as good as another. However, your "main2" function will *only* call "anyFunction2". The "main" function, on the other hand, will work for any desired callback function. – Pointy Aug 14 '14 at 16:51

1 Answers1

2

The comment by @Pointy is correct. Javascript supports "first-class functions" which is a fancy way of saying that you can think of a function like any other data type (e.g. string or number in javascript). See https://stackoverflow.com/a/705184/2308858.

This is powerful because it means your program can decide at runtime which function you want to run! You can even determine the "environment" in which your function executes at runtime, meaning that your function can use a global variable that has one value in one context and another value under a different set of conditions. This is called a closure, and can be pretty powerful.

By the way, in your example, it would be preferable to pass the jQuery context in through the function parameters rather than calling it directly. This way your anyFunction function has no knowledge of its environment; it is simply acting on the inputs it receives.

For example:

function main(statement, callback) {
    $("body").append("Statement: " + statement + "\n");
    callback( $("body") );    
}

function anyFunction( jqueryDomElement ) {
        jqueryDomElement.append("<p>I'm writing to a wall</p>");
}

main("This is test 1",anyFunction);
Community
  • 1
  • 1
Josh Padnick
  • 3,157
  • 1
  • 25
  • 33