Search code examples
jqueryoverridingextend

jquery how to override the class method?


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"......


Solution

  • 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/