如何在完全独立的.js文件中覆盖/扩展prototype.js类

Jam*_*lay 4 javascript magento prototypejs

我有一个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");
    },
}
Run Code Online (Sandbox Code Playgroud)

有人建议,但这不起作用我认为这是jQuery?

$.extend(obj_name.prototype, {
    newfoo : function() { alert('hi #3'); }
}
Run Code Online (Sandbox Code Playgroud)

don*_*tic 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');
  }
});
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴:http://jsfiddle.net/gqWDC/