j查询如何重写类方法



看起来这个问题很流行,但没有jQuery版本。

我有两个类,第二个是从第一个扩展而来的。

扩展方法从此处复制。

function UIButton(o){
    if (typeof(o) != 'undefined') $.extend(true, this, o); 
    this.setOutput=function(divname){
      alert("first");
    }
}
function UIButton2(o) {
    if (typeof(o) != 'undefined') $.extend(true, this, o);
    this.setOutput=function(divname) {
        alert("second");
    }
    return new UIButton(this);
}

根据 jquery 文档

第二个对象的方法

应通过使用 $.extend() 覆盖第一个对象的方法(具有相同的名称)。

但是,我在 html 中检查了它,发现第一个对象的函数仍然很好用。(警报"第一"...这使得它的子类不能覆盖函数。

所以我想问,这是如何发生的以及如何解决的。我想提醒"秒"...

首先扩展,然后设置新setOutput因此覆盖扩展方法)。

如果您更改顺序,它将起作用。

function UIButton(o){
    this.setOutput=function(divname){
      alert("first");
    }
    if (typeof(o) != 'undefined') $.extend(true, this, o); 
}
function UIButton2(o) {
    this.setOutput=function(divname) {
        alert("second");
    }
    if (typeof(o) != 'undefined') $.extend(true, this, o);
    return new UIButton(this);
}

仅在此示例的UIButton中需要,但我将其添加到两者中以备将来使用

http://jsfiddle.net/gaby/R26ec/演示

可以使用 jQuery 代理方法来覆盖类参考: http://api.jquery.com/Types/#Context.2C_Call_and_Apply

例如

(function() {
   // log all calls to setArray
   var proxied = jQuery.fn.setArray;
   jQuery.fn.setArray = function() {
   console.log( this, arguments );
   return proxied.apply( this, arguments );
  };
})();

最新更新