我对绑定函数的细节有疑问。这是示例:
// 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);
});
上面的代码片段来自[你不知道JS:this & Object Prototypes]这本书,问题是代码:
this.$elem.click(this.onClick.bind(this));
既然$elem
是赋值给button了,但是为什么this.onClick.bind(this)
可以绑定到Button.prototype.onClick的click事件上。这个语法让我很困惑,有没有人知道确切的原因?
非常感谢。
当您使用 jQuery 附加事件侦听器时,如下所示:this.$elem.click(...);
jQuery 会自动将元素(在本例中为button
元素)绑定到回调函数的上下文。换句话说,jQuery 使this
事件处理程序中的关键字引用触发事件的元素。
在您的情况下,onClick
函数的代码(in Button.prototype
) 期望this
引用Button
对象的当前实例,而不是 HTML 元素。因此,您必须使用bind
-将正确的对象显式绑定到回调函数的上下文this.onClick.bind(this)
。
TL; 博士
如果您没有使用bind
,this
回调函数中的关键字将引用被点击的button
元素而不是Button
对象实例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句