2012-05-12 12 views
0

この質問のように見えますが、jQueryのバージョンはありません。jqueryどのようにクラスメソッドをオーバーライドするには?

私は2つのクラスが最初のクラスから拡張されています。

延長方法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); 
} 

the jquery documentation

によれば、第2オブジェクトのメソッドは、$.extend()を用いて(同じ名前)最初のオブジェクトのメソッドをオーバーライドする必要があります。

しかし、私はそれをHTMLでチェックして、最初のオブジェクトの機能がまだうまく機能していることを発見しました。 (Alert "first" ...)これにより、そのサブクラスは関数をオーバーライドできなくなります。

だから私はこれがどのように起こり、どのように解決するかを尋ねたい。 "second"を警告したい......

答えて

1

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/

デモ

0

jQueryプロキシメソッドを使用してクラスをオーバーライドすることができます。 Ref: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); 
    }; 
})(); 
関連する問題