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?
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.
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.
Calling a function from within itself is called recursion and the simple answer is, yes.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With