Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

What is bind in javascript and when to use

What is bind in javascript?

Let’s take a quick overview of the below points in order to learn what is bind

  1. Javascript has a scope and scope creates a context for functions. For example,
  2. If you create a variable inside the function then that variable can be accessed inside the function itself.
  3. So context is a scope for the objects to which function belongs.
  4. That means this keyword can be used when the function tries to access an object property that has scope within the function. And
  5. You will get an error if you use this keyword when the function tries to access the property of an object which doesn’t belong to the function. Bind method helps to resolve this problem.

What is bind in javascript?
The bind() method helps in creating a new function that, when invoked or called, this newly created function will be having its this keyword set to the provided object value. In other words, it wraps the original function object.

Let’s take a below code snippet, where we have defined a method getAge, that returns the age of the person. When we call the method person.getAge it returns undefined. The reason is the function gets invoked at the global scope.

var person = {
  age: 30,
  getAge: function() {
    return this.x;
  }
}

var unboundGetAge = person.getAge;
console.log(unboundGetAge()); // The function gets invoked at the global scope
// expected output: undefined

var person = {
var boundGetAge = unboundGetAge.bind(module);
console.log(boundGetAge());
// expected output: 30

How to use bind in javascript?

We can solve the above issue with the method bind(). The simplest use of bind() is to call with a particular this value. Let’s look at the same code snippet with the bind method.

this.age = 9;    // this refers to global "window" object here in the browser
var person = {
  age: 30,
  getAge: function() { return this.age; }
};

person.getAge(); // 30

var retrieveAge = person.getAge;
retrieveAge();   
// returns 9 - The function gets invoked at the global scope

// Create a new function with 'this' bound to person
// New programmers might confuse the
// global var age with person's property age
var boundGetAge = retrieveAge.bind(person);
boundGetAge(); // 30