2
Contributors
1
Reply
12
Views
2 Years
Discussion Span
Last Post by phoenix254
0

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

Edited by phoenix254

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.