DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 12: Function Borrowing

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

Top comments (3)

Collapse
 
overflow profile image
overFlow • Edited

I don’t know if it’s jus me but this not a beginner lesson. I think it needs extra elaboration and examples.
It’s nice though !

Collapse
 
overflow profile image
overFlow • Edited

What level is this lesson ?! Is it intermediary or advanced ?!

Collapse
 
dhrn profile image
Dharan Ganesan

it is for intermediary level.