[removed] pass function as a parameter to another function, the code gets called in another order then i expect

后端 未结 2 1172
感情败类
感情败类 2021-02-05 07:29

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 ba

2条回答
  •  攒了一身酷
    2021-02-05 08:22

    $('#AddThirdParty').click(function() {
        var func = function() { // NOTE: no "new"
            alert('1');
            alert('2');
            alert('3');
        }
        alert('4');
        LoadHtml(func);
        alert('5');
    });
    function LoadHtml(funcToExecute) {
        //load some async content
        funcToExecute(); // 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() ...);

提交回复
热议问题