【发布时间】:2010-12-05 11:41:44
【问题描述】:
我知道 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's one 和 DUI),但它们会/确实遇到同样的问题。
那么在所有这些之后,在这些情况下我如何才能找到原始的this?
更新:事件处理程序(等)可以在jQuery.myBase 或插件本身中。
【问题讨论】:
标签: jquery events class object this