How bind method work in JavaScript

When I started working with JavaScript language, I faced issues many times related to “this” while making ajax call. In this case, the bind method helps me a lot. This can solve many other ways but bind method handy many times.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

MDN Defination
let boundFunc = func.bind(thisArg[, arg1[, arg2[, ...argN]]])

thisArg The value to be passed as the this parameter to the target function func when the bound function is called. The value is ignored if the bound function is constructed using the new operator.

If no arguments are provided to bind, or if the thisArg  is null or undefined, the this of the executing scope is treated as the thisArg for the new function.

The bind() function creates a new bound function, which is an exotic function object that wraps the original function object. Calling the bound function generally results in the execution of its wrapped function.

Let See Example:

Creating a bound function:

let user= {
    fName: 'singhak',
    lastName: '.in'
    getFullName: function() {
        console.log(this.fName +this.lastName);
    }
};

setTimeout(user.getFullName, 1000); //undefinedundefined

Let understand problem with above code. When we will run above code then we will get undefined as output.

This is because setTimeout() received the function user.getFullName separately from the user object. Therefore “this” getFullName function is not related to user any more.

Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem.

Let solve this using bind()

let user= {
    fName: 'singhak',
    lastName: '.in'
    getFullName: function() {
        console.log(this.fName+this.lastName);
    }
};
let fname = user.getFullName.bind(user)
setTimeout(fname , 1000); // singhak.in

Now understand what happen in above code.

The bind() function creates a new bound function, Here fname is a bound function. When a bound function is called, it calls the internal method target function, (here target function is getFullName) with the passed argument. (here the argument is user which is act as this for target function)

Now whenever you called bound function fname, it has instance of user object and you will get correct output.

One more example.

this.x = 9;    // 'this' refers to global 'window' object here in a browser
const module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX();
//  returns 81

const retrieveX = module.getX;
retrieveX();
//  returns 9; the function gets invoked at the global scope

//  Create a new function with 'this' bound to module
//  New programmers might confuse the
//  global variable 'x' with module's property 'x'
const boundGetX = retrieveX.bind(module);
boundGetX(); 
//  returns 81

Partially applied functions:

We can use of bind() is to make a function with pre-specified initial arguments.

These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed bound function at the time it is called.

function addArguments(arg1, arg2) {
  return arg1 + arg2
}
const result1 = addArguments(1, 2);
//  3

// Create a function with a preset first argument.
const addThirtySeven = addArguments.bind(null, 37);

const result2 = addThirtySeven(5); 
//  37 + 5 = 42 

const result3 = addThirtySeven(5, 10);
//  37 + 5 = 42 
//  (the second argument is ignored)

Partials are convenient when we don’t want to repeat the same argument over and over again

A function cannot be re-bound.

function Myname() {
  console.log(this.name); // singhak
}
//A function cannot be re-bound.
fname = Myname.bind( {name: "singhak"} ).bind( {name: "aksingh" } );

fname();

if the thisArg  is null or undefined, the this of the executing scope is treated as the thisArg for the new function.

let user = {
    name: "singhak",
    sayHi() {
     alert(this);
  },
}
u = user.sayHi.bind(null);
u(); // [Object Object] // this => window

Reference:

Leave a Reply