I have a problem about the detail of bind function. Here is the example:
// Parent class
function Widget(width, height) {
this.width = width || 50;
this.height = height || 50;
this.$elem = null;
}
Widget.prototype.render = function($where) {
if (this.$elem) {
this.$elem.css({
width: this.width + "px",
height: this.height + "px"
}).appendTo($where);
}
};
// Child class
function Button(width, height, label) {
// "super" constructor call
Widget.call(this, width, height);
this.label = label || "Default";
this.$elem = $("<button>").text(this.label);
}
// make `Button` "inherit" from `Widget`
Button.prototype = Object.create(Widget.prototype);
// override base "inherited" `render(..)`
Button.prototype.render = function($where) {
// "super" call
Widget.prototype.render.call(this, $where);
this.$elem.click(this.onClick.bind(this));
};
Button.prototype.onClick = function(evt) {
console.log("Button '" + this.label + "' clicked!");
};
$(document).ready(function() {
var $body = $(document.body);
var btn1 = new Button(125, 30, "Hello");
var btn2 = new Button(150, 40, "World");
btn1.render($body);
btn2.render($body);
});
The upper code snippet is from the book [You Don't Know JS: this & Object Prototypes], and the problem is the code :
this.$elem.click(this.onClick.bind(this));
Since $elem
is assigned to button, but why this.onClick.bind(this)
can be bind to the click event of Button.prototype.onClick. This syntax make me confused, is there any one know the exact reason?
Thanks a lot.
When you attach an event listener with jQuery, like so: this.$elem.click(...);
, jQuery automatically binds the element (in this case, the button
element) to the callback function's context. In other words, jQuery makes the this
keyword in an event handler to reference the element that fired the event.
In your case, the code of the onClick
function (in Button.prototype
), expects the this
to reference the current instance of the Button
object, and not the HTML element. Thus, you have to explicitly bind the correct object to the callback function's context using bind
- this.onClick.bind(this)
.
TL;DR
If you wouldn't have used bind
, the this
keyword in the callback function would refernce the clicked button
element instead of the Button
object instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.