Middle
What are the call, apply, and bind methods in JavaScript?
sobes.tech AI
Answer from AI
call, apply, and bind are methods available to all functions in JavaScript. They are used to control the execution context of a function (the value of this).
- call: Calls a function with a specified
thisvalue and individual arguments.// Example of using call function greet() { return "Hello, " + this.name + "!"; } const person = { name: "Ivan" }; console.log(greet.call(person)); // Output: Hello, Ivan! - apply: Calls a function with a specified
thisvalue and arguments provided as an array or array-like object.// Example of using apply function sum(a, b) { return this.base + a + b; } const context = { base: 10 }; const numbers = [5, 3]; console.log(sum.apply(context, numbers)); // Output: 18 - bind: Creates a new function that, when called, has its
thiskeyword set to the provided value. The original function is not called immediately.// Example of using bind const module = { x: 42, getX: function() { return this.x; } }; const unboundGetX = module.getX; console.log(unboundGetX()); // Output: undefined (this points to the global object) const boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // Output: 42 (this is bound to module)
Main differences:
| Method | Argument passing | Call | Return value |
|---|---|---|---|
| call | Separately (comma-separated) | Immediately | Result of the function execution |
| apply | As an array or array-like object | Immediately | Result of the function execution |
| bind | Separately (comma-separated) | Not immediately | New function with bound this |