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

后端 未结 2 1171
感情败类
感情败类 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() ...);

    0 讨论(0)
  • 2021-02-05 08:24
    $('#AddThirdParty').click(function() {
        var func = new function() {
            alert('1');
            alert('2');
            alert('3');
        }
        alert('4');
        LoadHtml(func);
        alert('5');
    });
    function LoadHtml(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 = new foo();
    

    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.

    0 讨论(0)
提交回复
热议问题