Javascript – How to override / extend a prototype.js class in a completely seperate .js file

javascriptmagentoprototypejs

I have a prototype.js class that I would like to extend to both add some new functions and override a couple of the functions already there.

in the example below I would like to add initAutocompleteNew and edit initAutocomplete to alert "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");
    },
}

someone suggested but that doesn't work I think it's jQuery?

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

Best Solution

This article should help out: http://prototypejs.org/learn/class-inheritance

It looks like you're defining your classes the 'old' way as described in the first example on that page. Are you using 1.7?

Assuming you are using 1.7, if you wanted to override or add methods to your class, you can use 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');
  }
});

Here's a fiddle: http://jsfiddle.net/gqWDC/