Day 12: Function Borrowing

Dharan Ganesan - Jul 26 '23 - - Dev Community

Understanding Function Borrowing:

Function borrowing enables us to use a method from one object and apply it to another object. This can be achieved by invoking a method from one object but setting the this keyword inside the method to point to a different object. It is accomplished through the use of .call(), .apply(), or .bind(), all of which exist to explicitly set this on the method we are borrowing.

  • call method:

The call() method is used to invoke a function with a specified this value and arguments provided individually.

functionName.call(thisArg, arg1, arg2, ...);
Enter fullscreen mode Exit fullscreen mode
const person1 = {
  name: 'Alice',
  greet: function(greeting) {
    console.log(`${greeting}, I'm ${this.name}.`);
  },
};

const person2 = {
  name: 'Bob',
};

person1.greet.call(person2, 'Hello');
// Output: Hello, I'm Bob.
Enter fullscreen mode Exit fullscreen mode
  • apply method:

The apply() method is similar to call(), but it takes an array-like object as its second argument to pass arguments to the function.

functionName.apply(thisArg, [arg1, arg2, ...]);
Enter fullscreen mode Exit fullscreen mode
const person1 = {
  name: 'Alice',
  greet: function(greeting, age) {
    console.log(`${greeting}, I'm ${this.name}, and I'm ${age} years old.`);
  },
};

const person2 = {
  name: 'Bob',
};

person1.greet.apply(person2, ['Hello', 30]);
// Output: Hello, I'm Bob, and I'm 30 years old.
Enter fullscreen mode Exit fullscreen mode
  • bind method:

The bind() method creates a new function with a specified this value and any provided initial arguments. Unlike call() or apply() that executes the function immediately, bind() returns a new function that can be called later.

const newFunction = functionName.bind(thisArg, arg1, arg2, ...);
Enter fullscreen mode Exit fullscreen mode
const person1 = {
  name: 'Alice',
  greet: function(greeting) {
    console.log(`${greeting}, I'm ${this.name}.`);
  },
};

const person2 = {
  name: 'Bob',
};

const greetBob = person1.greet.bind(person2, 'Hi');
greetBob();
// Output: Hi, I'm Bob.
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player