gpt4 book ai didi

javascript - 书中关于jQuery onclick绑定(bind)函数的使用【你不懂JS : this & Object Prototypes]

转载 作者:行者123 更新时间:2023-12-01 02:55:15 27 4
gpt4 key购买 nike

我对绑定(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({
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);
});

上面的代码片段来自《You Don't Know JS: this & Object Prototypes》一书,问题出在代码上:

this.$elem.click(this.onClick.bind(this));

既然$elem被分配给了按钮,但是为什么this.onClick.bind(this)可以绑定(bind)到Button.prototype.onClick的点击事件。这个语法让我很困惑,有谁知 Prop 体原因吗?

非常感谢。

最佳答案

当您使用 jQuery 附加事件监听器时,如下所示:this.$elem.click(...);,jQuery 会自动绑定(bind)该元素(在本例中为 button 元素)到回调函数的上下文。换句话说,jQuery 在事件处理程序中使用 this 关键字来引用触发该事件的元素。

在您的情况下,onClick 函数的代码(在 Button.prototype 中)期望 this 引用当前的实例Button 对象,而不是 HTML 元素。因此,您必须使用 bind - this.onClick.bind(this) 将正确的对象显式绑定(bind)到回调函数的上下文。

TL;DR

如果您没有使用 bind,则回调函数中的 this 关键字将引用单击的 button 元素,而不是 Button 对象实例。

关于javascript - 书中关于jQuery onclick绑定(bind)函数的使用【你不懂JS : this & Object Prototypes],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46740981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com