I am trying to understand javascript bind method. I have read this other SO post about bind method and learned a great deal. One of the posts linked to javascripture where I played around with bind.
To my understanding, and according to mozilla's site, bind "creates a new function that 'binds' this to the bound object."
var Button = function(content) {
this.content = content; //stores content into this.content property
};
Button.prototype.click = function() { //adds click method
console.log(this.content + ' clicked');
}
var myButton = new Button('OK');
console.log(myButton.content); //OK
myButton.click(); //OK clicked
var looseClick = myButton.click;
console.log(looseClick.content); //undefined
looseClick(); //undefined clicked
var notLooseClick = myButton.click.bind(myButton);
console.log(notLooseClick.content); //undefined
notLooseClick(); //OK clicked
My confusion is the last var, notLooseClick. I don't understand why notLooseClick.content returns undefined while notLooseClick(); returns 'OK clicked'. I had expected 'OK' to be bound to notLooseClick.content.
How can I bind notLooseClick so when I call notLooseClick.content, it is bound to Button's this.content, so when I type notLooseClick.content it returns 'OK'? Why does bind() behave this way?
binddoes, that is, if you bind the function to the object it needs, you don't need to call it usingobj.func, you can dovar func = obj.func.bind(obj);and callfunc()and yourobjwill still be thethisin that call.notLooseClick.contentyou're trying to get attributecontentfrom function and not frombutton.contentis never going to be a property of thefunctionit's a property of thethisin the functioncontentstays a property ofmyButton(orthis):console.log(myButton.content);. It does not become a property ofmyButton.click,looseClickornotLooseClick.