Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 关于书中jQuery onclick bind函数的用法[您不知道JS:this&;Object原型]_Javascript_Jquery - Fatal编程技术网

Javascript 关于书中jQuery onclick bind函数的用法[您不知道JS:this&;Object原型]

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

我对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);
});
既然
$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));