0

Looks like this question is popular, but there is no jQuery version.

I have two classes the second is extended from the first one.

The extension method is copied from here.

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);
}

According to the jquery documentation

The second object's method should override the first object's method (with same name) by using $.extend().

However I check it in the html and found the first object's function still work like good. (Alert "first"...) This makes its subclass cannot override the function.

So I want to ask, how this happen and how to solve it. I want to alert "second"......

kapa
  • 77,694
  • 21
  • 158
  • 175
Fenix Lam
  • 386
  • 6
  • 22

2 Answers2

1

You extend first, and then you set the new setOutput (so you overwrite the extended method).

If you change the order it will work..

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);
}

(only needed in the UIButton for this example, but i added it to both for future usage)

Demo at http://jsfiddle.net/gaby/R26ec/

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

You can use jQuery proxy method to override class Ref: http://api.jquery.com/Types/#Context.2C_Call_and_Apply

For example

(function() {
   // log all calls to setArray
   var proxied = jQuery.fn.setArray;
   jQuery.fn.setArray = function() {
   console.log( this, arguments );
   return proxied.apply( this, arguments );
  };
})();
Tofeeq
  • 2,523
  • 1
  • 23
  • 20