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


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));
//////more was here

    initAutocomplete : function(url, destinationElement){

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:

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:

  initAutocomplete: function(url, destinationElement) {
    // Your new implementation
    // This will override what was previously defined
  someNewMethod: function() {
    // This will add a new method, `someNewMethod`

Here's a fiddle: