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:
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."
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."
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: