Search code examples
javascriptunobtrusive-javascript

When should I use call() vs invoking the function directly?


I've got a JavaScript application that uses a lot of callbacks. A typical function will take a callback, and wrap it with another callback.

Namespace.foo = function( arg, their_on_success ) {
    var my_on_success = function( result ) {
        console.log( 'my_on_success() called' );
        if( 'function' === typeof their_on_success ) {
              their_on_success( result );
        }
    }
    something( arg, my_on_success );
};

Given the above example, when should such a setup us the native call() method (passing the result var as the second argument) rather than invoking their_on_success() and passing in the result via function invocation?


Solution

  • call() is used to change the this value of the function:

    var obj = {a: 0};
    method.call(obj, "parameter");
    function method(para) {
        this.a == 0; // true <-- obj is now this
    }