EXPLAIN THE BIND() METHOD IN JAVASCRIPT?

Bind creates a new function that will have this set to the first parameter passed to bind().

Here's an example that shows how to use bind to pass a member method around that has the correct** this**:

var Button = function(content) { 
  this.content = content;
};

Button.prototype.click = function() {
  console.log(this.content + ' clicked');
}



var myButton = new Button('OK');
myButton.click();

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

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

Which prints out:

OK clicked
undefined clicked
OK clicked

You can also add extra parameters after the 1st parameter and bind will pass in those values to the original function before passing in the extra parameters you pass to the bound function:

// Example showing binding some parameters
*

var sum = function(a, b) {
  return a + b;
};*





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

Which prints out:

15

I copied this form here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.