开发者

JavaScript/JQuery - can you pass a reference to a function and then execute it?

Based on the JavaScript example below, is there a way to pass a reference to function f to the promptForProceed function and have it conditionally executed in promptForProceed?

Could you also do this if the ffunction took some parameters (ie: f(a, b, c) { ... })?

function f() {
    //Do stuff..
}

function promptForProceed(myFunction) {  // <------ PASS FUN开发者_JAVA技巧CTION AS PARAMETER
    $("#div-dialog-proceed").dialog({
        modal: true,
        buttons: {
            "Stay on current page": function () {
                $(this).dialog("close");
            },
            "Continue": function () {
                $(this).dialog("close");
                myFunction(); // <---------  CALL FUNCTION
            }
        }
    });
}

Update: Think I like the option of using an anonymous function parameter:

promptForProceed(function() { //Do stuff like call f(a,b,c) });


Yes, but you should probably not name both of them f or it will be confusing what is going on. The line you called f() on is calling the parameter, not the function f (unless that's what you passed)

To pass parameters, pass promptForProceed(myFunction, a, b, c) and then call with myFunction(a, b, c)


of course you can. Functions are objects!


Yes. Functions are first-class objects in JavaScript and can be passed as parameters.

In fact, your syntax is correct. It should work already :)


Yes you can. What you have should work. Passing parameters in is fine too.

You should also look in to the call method of function which allows you to set the scope

myFunction.call(object);

The apply method allows you to pass arguments in as an array.

myFunction.apply([param1, param2]);

Also, you should understand 'closures' and how scope works when passing functions around like this. http://en.wikipedia.org/wiki/Closure_(computer_science)#JavaScript


promptForProceed(f, f_parameter)

Then pass f_parameter to f()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜