我正在使用jQuery並嘗試將一些基本的Javascript OOP原則應用於控制懸停行爲的一組函數。但是,我無法弄清楚如何讓「this」關鍵字引用我創建的對象的實例。我的示例代碼是:使用面向對象的jQuery
var zoomin = new Object();
zoomin = function() {
// Constructor goes here
};
zoomin.prototype = {
hoverOn: function() {
this.hoverReset();
// More logic here using jQuery's $(this)...
},
hoverReset: function() {
// Some logic here.
}
};
// Create new instance of zoomin and apply event handler to matching classes.
var my_zoomin = new zoomin();
$(".some_class").hover(my_zoomin.hoverOn, function() { return null; });
在上述代碼中的問題的行是調用「this.hoverReset()」的hoverOn內部()函數。由於「this」現在指的是被擱置的元素,因此它不能按預期工作。我基本上喜歡爲該對象的實例(my_zoomin)調用函數hoverReset()。
有沒有辦法做到這一點?
謝謝!
+1對於很好的解釋 – rzetterberg 2011-05-02 01:14:31
謝謝你的出色答案。它確實爲我澄清了一些事情:-)我一定會考慮將它變成一個插件。 – Ralph 2011-05-02 01:28:51