JavaScript
< 1 minute read

bind() method creates a new function, when called has its this keyword set to the provided value

Let’s have a look at a sample code, on how to use the bind() function:


const person = {
    age: 20,
    getAge: function() {
        return this.age;
    }
}

const unBoundedGetAge = person.getAge;

console.log(unBoundedGetAge())

If we run the code, we’ll get undefined as the output.

We need to bind the getAge method to the person object, in order to use the this reference.


const person = {
    age: 20,
    getAge: function() {
        return this.age;
    }
}

const unBoundedGetAge = person.getAge;

const boundGetAge = unBoundedGetAge.bind(person)

console.log(boundGetAge())

Running the code now outputs the actual age: 20

bind() function is useful when the function need to be called in future events.