Both call and apply are methods in JavaScript that can be used to invoke a function with a specified this value and a list of arguments. However, they differ in how they pass arguments to the function.
The call method allows you to pass arguments to the function as a comma-separated list. The first argument is the this value, and the subsequent arguments are the function arguments. For example, the following code uses call to invoke the foo function with the obj object as the this value and two arguments:
function foo(arg1, arg2) {
console.log(this, arg1, arg2);
}
var obj = { name: 'John' };
foo.call(obj, 'Hello', 'World');
// Output: { name: 'John' }, 'Hello', 'World'
In this example, the this value is set to the obj object, and the arguments 'Hello' and 'World' are passed to the foo function.
The apply method, on the other hand, allows you to pass arguments to the function as an array. The first argument is the this value, and the second argument is an array of function arguments. For example, the following code uses apply to invoke the foo function with the obj object as the this value and an array of two arguments:
function foo(arg1, arg2) {
console.log(this, arg1, arg2);
}
var obj = { name: 'John' };
foo.apply(obj, ['Hello', 'World']);
// Output: { name: 'John' }, 'Hello', 'World'
In this example, the this value is set to the obj object, and the array ['Hello', 'World'] is passed to the foo function.
In summary, the main difference between call() and apply () is how they pass arguments to the function. call passes arguments as a comma-separated list, while apply passes arguments as an array.
Comments (0)