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?