Use of call, apply, and bind in JavaScript

In JavaScript, call, apply, and bind are methods used to manipulate the this value inside a function.

  1. call: The call method is used to invoke a function with a specified this value and individual arguments passed directly.

     javascriptCopy codefunction greet(name) {
         console.log(`Hello, ${name}! I'm ${this.title}`);
     }
    
     const context = { title: 'ChatGPT' };
     greet.call(context, 'User');
    
  2. apply: The apply method is similar to call, but it accepts arguments as an array.

     javascriptCopy codefunction greet(name) {
         console.log(`Hello, ${name}! I'm ${this.title}`);
     }
    
     const context = { title: 'ChatGPT' };
     greet.apply(context, ['User']);
    
  3. bind: The bind method creates a new function with the same body as the original function but with a fixed this value. It doesn't immediately invoke the function but returns a new function that can be called later.

     javascriptCopy codefunction greet(name) {
         console.log(`Hello, ${name}! I'm ${this.title}`);
     }
    
     const context = { title: 'ChatGPT' };
     const boundGreet = greet.bind(context);
    
     boundGreet('User');
    

In each of these methods, the first argument is the this value to be used in the function. For call and apply, subsequent arguments (or an array of arguments in the case of apply) are the arguments passed to the function. For bind, it only sets the this value, and you need to call the returned function separately.