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

后端 未结 2 1176
感情败类
感情败类 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: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.

提交回复
热议问题