2012-04-26 25 views
4

我有一個prototype.js類,我想擴展它來添加一些新的函數並覆蓋已經存在的一些函數。如何在完全獨立的.js文件中覆蓋/擴展prototype.js類

在下面的示例中,我想添加initAutocompleteNew並編輯initAutocomplete以提醒「新建」。

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嗎?

假設你使用的是1.7,如果你想重寫或添加方法,你的類,你可以使用Class.addMethods

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

是的,我現在用的1.7是prefectly工作感謝dontGoPlastic。 – 2012-04-29 18:02:06

+0

有沒有辦法從覆蓋中調用父方法? – 2013-10-30 10:57:31

+0

@Tim是不是$超級不工作(詳細的類繼承職位)? – dontGoPlastic 2013-10-31 03:02:51