1

我知道 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插件本身或插件本身中。

4

4 回答 4

2

您需要在适当的范围内引用它。

jQuery.fn.myPlugin = function() {
   var $this = this;  // Scope it up!
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           jQuery('#someEl').click( this.onClick );
       },

       onClick: function(e) {
           $this.bar();
       }
  }
}
于 2009-10-09T21:13:34.050 回答
0

看起来他们正在jQuery 中解决这个问题,根据评论应该是 1.3.3 的一部分

于 2009-10-09T22:15:26.813 回答
0

另一种选择是遵循具有函数的原型方法(实际上与我的其他答案相同,但以更简洁的方式),正如在这个问题bind()中指出的那样,例如:

if (!Object.bind) {
    Function.prototype.bind= function(owner) {
        var that= this;
        var args= Array.prototype.slice.call(arguments, 1);
        return function() {
            return that.apply(owner,
                args.length===0? arguments : arguments.length===0? args :
                args.concat(Array.prototype.slice.call(arguments, 0))
            );
        };
    };
}


jQuery.fn.myPlugin = function() {
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           jQuery('#someEl').click( this.onClick.bind( this ) );
       },

       onClick: function(e) {
           this.bar(); // this works
       }
  }
}
于 2009-10-09T22:05:43.913 回答
0

我想到这样做的唯一方法,我不太喜欢并因此提出这个问题,方法如下:

jQuery.myBase = {
    bar: function() { ... }
}

jQuery.fn.myPlugin = function() {
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           var self = this;
           jQuery('#someEl').click( function(e) {
                this.onClick.apply( self, arguments );
           };
       },

       onClick: function(e) {
           // this works
           this.bar();
       }
  }
}
于 2009-10-09T21:12:33.027 回答