我知道 jQuery 不是为使用类模型而设计的,但我确实可以扩展一个基类,因为它完全符合我的需求。
我开始做以下事情:
jQuery.myBase = {
foo: 'bar',
bar: function() { ... }
}
jQuery.fn.myPlugin = function() {
$.extend( this, jQuery.myBase, {
oof: 'rab',
rab: function() { ... }
}
}
一切正常,我可以通过this
. 直到我尝试添加诸如 jQuery 事件处理程序(等)之类的东西,它将事件目标应用于this
.
因此,使用以下内容:
jQuery.myBase = {
bar: function() { ... }
}
jQuery.fn.myPlugin = function() {
jQuery.extend( this, jQuery.myBase, {
init: function() {
jQuery('#someEl').click( this.onClick );
},
onClick: function(e) {
// this now references the element I bound the event to (<div id="someEl" />)
// so the following doesn't work
this.bar();
}
}
}
我发现了一些适用于 jQuery 的类创建和继承的东西(例如John Resig 的和DUI),但那些会/确实遇到同样的问题。
那么在所有这些之后,在这些情况下我如何获得原件this
?
更新:事件处理程序(等)可以在jQuery.myBase
插件本身或插件本身中。