As per definition 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.
if you remove bind()
method then this
keyword shows the global object because the way javascript this
keyword works. To understand the working of this
keyword you can refer here.
To understand the working of bind()
method here are the code snippet.
var obj = {
key: 'xyz',
display: function(){
console.log(this.key);
}
};
obj.display(); // expected output: xyz
const unboundDisplay = obj.display;
unboundDisplay(); // The function gets invoked at the global scope
// expected output: undefined
const boundDisplay = unboundDisplay.bind(obj);
boundDisplay(); // expected output: xyz
To summarize bind()
method is used when we assign this function reference to some other variable