2017-10-14 37 views
0

我有一個關於綁定函數細節的問題。這裏是例子:關於jQuery綁定函數的用法

// 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.$elem.click(this.onClick.bind(this)); 

由於$elem被分配給按鈕,但爲什麼this.onClick.bind(this)可以是 綁定到Button.prototype.onClick的點擊事件。這個語法讓我迷惑,,有沒有人知道確切的原因?

非常感謝。

回答

1

當您使用jQuery附加事件偵聽器時,如下所示:this.$elem.click(...);,jQuery自動將元素(本例中爲button元素)綁定到回調函數的上下文。換句話說,jQuery使事件處理程序中的關鍵字this引用引發該事件的元素。

在你的情況下,onClick函數(在Button.prototype)的代碼,預計this引用Button對象的當前實例,而不是HTML元素。因此,您必須使用bind - this.onClick.bind(this)將正確的對象顯式綁定到回調函數的上下文。

TL; DR

如果你不會用bind,在回調函數的this關鍵字將refernce的點擊button元素,而不是Button對象實例。