2012-05-12 3 views
0

이 질문은 인기가 있지만 jQuery 버전은 없다고 생각됩니다.jquery 클래스 메서드를 재정의하는 방법?

두 번째 클래스는 두 번째 클래스가 첫 번째 클래스에서 확장되었습니다.

확장 방법 is copied from here. $.extend()를 사용하여 (동일한 이름) 제 객체의 메소드를 오버라이드 (override)의 제 2 목적에있어서 the jquery documentation

따르면

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

.

그러나 나는 HTML에서 그것을 확인하고 첫 번째 객체의 기능이 여전히 잘 작동하는 것을 발견했습니다. (Alert "first"...) 이것은 서브 클래스가 함수를 오버라이드 (override) 할 수 없게 만든다.

그래서 어떻게되는지, 그리고 어떻게 해결해야하는지 묻고 싶습니다. "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); 
    }; 
})(); 
관련 문제