javascript tutorial - [Solved-5 Solutions] call and apply - javascript - java script - javascript array



Problem:

What is the difference between using call and apply to invoke a function?

Solution 1:

The difference is that apply lets we invoke the function with arguments as an array; callrequires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma." Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

Sample code:

function theFunction(name, profession) {
    console.log("My name is " + name + " and we are a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

// Output: 

// My name is John and WE am a fireman.
// My name is Susan and WE am a school teacher.
// My name is Claude and WE am a mathematician.
// My name is Matthew and WE am a physicist.
click below button to copy the code. By JavaScript tutorial team

Solution 2:

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."

// assuming we have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);
click below button to copy the code. By JavaScript tutorial team

Solution 3:

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."

// assuming we have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);
click below button to copy the code. By JavaScript tutorial team

Solution 4:

  • Call() takes comma-separated arguments, ex:
    • .call(scope, arg1, arg2, arg3)
  • and apply() takes an array of arguments, ex:
    • .apply(scope, [arg1, arg2, arg3])

Solution 5:

I'd like to show an example, where the 'valueForThis' argument is used:

Array.prototype.push = function(element) {
   /*
   Native code*, that uses 'this'       
   this.put(element);
   */
}
var array = [];
array.push(1);
array.push.apply(array,[2,3]);
Array.prototype.push.apply(array,[4,5]);
array.push.call(array,6,7);
Array.prototype.push.call(array,8,9);
//[1, 2, 3, 4, 5, 6, 7, 8, 9] 
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - call and apply