开发者

Different syntax for passing methods as arguments?

I'm currently trying to teach myself more about javascript, and I find myself stumbling over the syntax for passing a method as an argument to another method call. Say you have two functions like these:

    function FirstFunction()
    {
        DoesSomething();
    }


    function SecondFunction(func)
    {
        func();
    }

In actually passing the FirstFunction to the SecondFunction, I seem to see a wild variety of variations on doing so:

    SecondFunction(FirstFunction);

or

    SecondFunction("FirstFunction()");

or sometimes, if FirstFunction was defined as follows:

    var thisisafunction = function FirstFuncti开发者_如何学Con()
    {
        DoesSomething();
    }

    SecondFunction(thisisafunction);

I'm guessing there's no "one right way" to do this, so when is it appropriate to use each way of passing a function? Is it better to use one way over another in a certain situation?


Passing a string is always bad. It only works with functions like setTimeout which automatically eval() strings and it's bad since it runs in the global context.

If you just want to pass a plain function without creating a closure or passing arguments, passing the function without () is fine:

myFunc(someCallbackFunc);

If you need to pass arguments or want a closure so you can access some non-global variables inside that function, use an anonymous function:

myFunc(function() {
    someCallbackFunc('meow');
});

Of course you can also assign the function to a variable first:

var cb = function() {
    someCallbackFunc('meow');
};
myFunc(cb);

While var cb = function someName() {}; is valid, I'd recommend against giving your function expressions names - it's not supported by all browsers. The only advantage is having a function name in debuggers anyway...


First let me clear something. You can define functions both as:

function name() { ... };

or assign it to a variable

var myFunc = function() { ... };

you don't mix both by doing

var myFunc = function name() { ... };  //WRONG

since name won't be binded to anything.

After this, the most usual way of passing functions as arguments, is just to pass the function object without the function call operator "()", which means the function object is not executed.

var func1 = function() { console.log("func1 here") };

var func2 = function(f) {  f(); };

func2(func1);

Also, passing the function as String with the function call operator means that the receiving function will have to evaluate that using eval() for the function argument to be executed. It is not recommended.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜