Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
buley Avatar asked Oct 19 '11 17:10

buley


People also ask

What is the difference between using call () and apply () to invoke a function with multiple arguments?

The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.

What is difference between call and function?

A function is a block of code that does a particular operation and returns a result. It usually accepts inputs as parameters and returns a result. The parameters are not mandatory. A function call is the code used to pass control to a function.

Could a method function invoke or call itself?

Calling a function from within itself is called recursion and the simple answer is, yes.

What does invoking a method mean?

The method invocation statement calls a method defined for the class of a reference variable. This statement is used for methods of user classes, system classes, and external classes. You can invoke any method defined for the class of the reference variable or any inherited method from the variable's superclasses.


1 Answers

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
}
like image 93
Joe Avatar answered Sep 20 '22 01:09

Joe