Call, Apply, Bind in Java Script | Frontend Interview Questions

Table of Contents

1. call()

Definition - 
call() provides a new value of this to the function/method. With call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

Syntax - 
fn.call(thisArg, arg1, arg2, ...);

Source - here

Let’s understand call() with an example

Example 1

In the below example, user2 is an object defined and declared once and inherited/used by the different user object

//Eg 1
let user = {
  show: function () {
    console.log("show here", this.name);
  },
};

let user2 = {
  name: "himanshu",
};

user.show.call(user2);

Example 2 –

In the below example (eg 2)

  • “greeting” is a global object/variable and “greeting” inside an messenger object is an local/block scope variable
  • By default this refer to the global scope, so in the first function call , this point to “Hi”
  • In second function all , this is changes to the object , so now this is pointing to its own variable which is “Hello”
//eg 2
//by default this reffer to global object

//global object
var greeting = "Hi";

//messenger object is declared once and user many time using call()
var messenger = {
  greeting: "Hello",
};

function say(name) {
  console.log(this.greeting + " " + name);
}

function age(age) {
  console.log("2nd method", this.greeting, age);
}

say.call(this, "jhon"); //here this is referring to the global scope
say.call(messenger, "jhon"); //changed this scope by passing object as this value
age.call(this, 10); 

Example 3

Constructor chaining with call()

function Box(height, width) {
  this.height = height;
  this.width = width;
}

function Widget(height, width, color) {
  Box.call(this, height, width);
  this.color = color;
}

let widget = new Widget("red", 100, 200);

console.log(widget);

Question for you guys ??????

const car = {
  name: 'car',
  start() {
    console.log('Start the ' + this.name);
  },
  speedUp() {
    console.log('Speed up the ' + this.name);
  },
  stop() {
    console.log('Stop the ' + this.name);
  },
};

const aircraft = {
  name: 'aircraft',
  fly() {
    console.log('Fly');
  },
};

car.start.call(aircraft);
car.speedUp.call(aircraft);
aircraft.fly();

Comment below your answers?


2. apply()

The Function.prototype.apply() method allows you to call a function with a given this value and arguments provided as an array. Here is the syntax of the apply() method:

Syntax -
fn.apply(thisArg, [args])  
   
Source - here

Diffeence between call() and apply()

call()apply()
takes individual argumenttakes argument as an array
fn.call(thisArg, arg1, arg2, …);fn.apply(thisArg, [args])

Example

const person = {
  fullName: function (city, country) {
    console.log(
      this.firstName + " " + this.lastName + "," + city + "," + country
    );
  },
};

const person1 = {
  firstName: "John",
  lastName: "Doe",
};

person.fullName.apply(person1, ["Oslo", "Norway"]);

3.bind()

The bind() method returns a new function, when invoked, has its this sets to a specific value.
Syntax -
fn.bind(thisArg[, arg1[, arg2[, ...]]])

Source - here

bind allows-

  • set the value of “this” to an specific object. This becomes very helpful as sometimes this is not what is intended.
  • reuse methods
  • curry a function

Example 1 –

var myButton = {
  content: 'OK',
  click() {
    console.log(this.content + ' clicked');
  }
};

myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton


output - 
OK clicked
undefined clicked
OK clicked

Source - here

Example 2

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Practice here (constructor, bind, this , apply, call)- link

Question for you

// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));

Comment on the output ???

Understand call(), apply(), and bind() in one code (fast) :

let user1 = {
  name: "shekhar",
};
function about(place, age) {
  console.log(" name : ", this.name + ", place: " + place + ", age: " + age);
}

let user2 = {
  name: "himanshu",
};

about.call(user2, "dtg", 24); //call takes individual argument
about.apply(user2, ["dtg", 24]); //apply take argument in an array

var ab = about.bind(user2, "delhi", 28); //bind return a new function as a copy function , so that it can be reused 
ab();

Please comment on how you liked this article. If it helped, please reply with “helpful”, and if it didn’t, please reply with “improve it”.

Thank you for reading.

Help Others

Leave a Reply

Your email address will not be published. Required fields are marked *