2012-04-26 7 views
4

prototype.jsクラスを拡張して、いくつかの新しい関数を追加し、そこに既にある関数のいくつかをオーバーライドします。完全に分離された.jsファイルでprototype.jsクラスをオーバーライド/拡張​​するには

以下の例では、initAutocompleteNewを追加し、initAutocompleteを編集して「new」を警告します。

Varien.searchForm = Class.create(); 
Varien.searchForm.prototype = { 
    initialize : function(form, field, emptyText){ 
     this.form = $(form); 
     this.field = $(field); 
     this.emptyText = emptyText; 

     Event.observe(this.form, 'submit', this.submit.bind(this)); 
     Event.observe(this.field, 'focus', this.focus.bind(this)); 
     Event.observe(this.field, 'blur', this.blur.bind(this)); 
     this.blur(); 
    }, 
//////more was here 

    initAutocomplete : function(url, destinationElement){ 
      alert("old"); 
    }, 
} 

誰かが示唆したが、うまくいかないと思うのは、jQueryだと思いますか?

$.extend(obj_name.prototype, { 
    newfoo : function() { alert('hi #3'); } 
} 

答えて

6

この記事は助ける必要があります:http://prototypejs.org/learn/class-inheritance

そのページの最初の例で説明したように、あなたが「古い」方法を、あなたのクラスを定義しているように見えます。あなたは1.7を使用していますか?

Varien.searchForm.addMethods({ 
    initAutocomplete: function(url, destinationElement) { 
    // Your new implementation 
    // This will override what was previously defined 
    alert('new'); 
    }, 
    someNewMethod: function() { 
    // This will add a new method, `someNewMethod` 
    alert('someNewMethod'); 
    } 
}); 

はここでフィドルです:http://jsfiddle.net/gqWDC/

+0

うん、私はprefectly働い1.7を使用しています、あなたのクラスにメソッドをオーバーライドしたり、追加したい場合は、あなたがClass.addMethodsを使用することができ、あなたが1.7を使用していると仮定すると、

ありがとうdontGoPlastic。 –

+0

オーバーライドから親メソッドを呼び出す方法はありますか? –

+0

@Tim $ superは機能しません(クラスの継承ポストに詳細があります)? – dontGoPlastic

関連する問題