Skip to content Skip to sidebar Skip to footer

Javascript: Pass Function As A Parameter To Another Function, The Code Gets Called In Another Order Then I Expect

i want to pass a function to another function as a parameter. I want to do that because the latter function calls an async Jquery method and AFTER that gives a result back, i want

Solution 1:

$('#AddThirdParty').click(function() {
    var func = function() { // NOTE: no "new"alert('1');
        alert('2');
        alert('3');
    }
    alert('4');
    LoadHtml(func);
    alert('5');
});
functionLoadHtml(funcToExecute) {
    //load some async contentfuncToExecute(); // NOTE: parentheses
}

Two errors: the syntax for anonymous functions does not include the keyword new; and JavaScript requires parentheses for function calls, even if functions do not take any arguments. When you just say funcToExecute, that is just a variable giving its value in a context where nothing is using that value (kind of like writing 3; as a statement).

You might notice that you already know how to use anonymous functions: you did not write $('#AddThirdParty').click(new function() ...);

Solution 2:

$('#AddThirdParty').click(function() {
    var func = newfunction() {
        alert('1');
        alert('2');
        alert('3');
    }
    alert('4');
    LoadHtml(func);
    alert('5');
});
functionLoadHtml(funcToExecute) {
    //load some async content
    funcToExecute;
}

The new keyword creates an object from the function. This means the function (which is anonymous) gets called immediatly. This would be the same as

var foo = function() {
    alert("1");
    alert("2");
    alert("3");
}
var func = newfoo();

This means your creating a new object (not a function!) and inside the constructor your alert 1,2,3. Then you alert 4. Then you call LoadHtml which does nothing, then you alert 5.

As for

funcToExecute;

The funcToExecute is just a variable containing a function. It actually needs to be executed.

Post a Comment for "Javascript: Pass Function As A Parameter To Another Function, The Code Gets Called In Another Order Then I Expect"