Javascript 关于书中jQuery onclick bind函数的用法[您不知道JS:this&;Object原型]
我对bind函数的细节有一个问题。以下是一个例子:Javascript 关于书中jQuery onclick bind函数的用法[您不知道JS:this&;Object原型],javascript,jquery,Javascript,Jquery,我对bind函数的细节有一个问题。以下是一个例子: // 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({ w
// 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);
});
既然$elem
被分配给按钮,为什么这个.onClick.bind(这个)
可以
绑定到Button.prototype.onClick的click事件。这个语法让我
困惑,有人知道确切的原因吗
非常感谢 使用jQuery附加事件侦听器时,如下所示:
this.$elem.click(…)代码>,jQuery会自动将元素(在本例中为按钮
元素)绑定到回调函数的上下文。换句话说,jQuery使事件处理程序中的this
关键字引用触发事件的元素
在您的例子中,onClick
函数的代码(在Button.prototype
中)期望this
引用Button
对象的当前实例,而不是HTML元素。因此,必须使用bind
-this.onClick.bind(this)
将正确的对象显式绑定到回调函数的上下文
TL;DR
如果您没有使用bind
,回调函数中的this
关键字将引用单击的按钮
元素,而不是按钮
对象实例。当您使用jQuery附加事件侦听器时,如下所示:this.$elem.click(…)代码>,jQuery会自动将元素(在本例中为按钮
元素)绑定到回调函数的上下文。换句话说,jQuery使事件处理程序中的this
关键字引用触发事件的元素
在您的例子中,onClick
函数的代码(在Button.prototype
中)期望this
引用Button
对象的当前实例,而不是HTML元素。因此,必须使用bind
-this.onClick.bind(this)
将正确的对象显式绑定到回调函数的上下文
TL;DR
如果您没有使用bind
,回调函数中的this
关键字将引用单击的按钮
元素,而不是按钮
对象实例
this.$elem.click(this.onClick.bind(this));