Search code examples
javascriptprototypejsoverriding

Override prototype javascript object


I have the following in prototype.js:

    Ajax.Base = Class.create({
    initialize: function(options) {
    alert('in original');
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

I am trying to add another option, but I don't want to modify the existing prototype library, but extend it so that it will have my new option. I have created a second js file that gets loaded after prototype.js that includes the following:

  Ajax.Base = Class.create({
  initialize: function(options) {
    alert('in override');
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true,
      on401: function() { window.location.href="/logout.jsp"; }
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

The alert in the override object never gets called, but it continues to use the original object. I must be missing something or the Class.create is doing things dynamically after I have tried to redefine the object.


Solution

  • I found a way to make it work using Class#addMethods():

    Ajax.Base.addMethods({
        initialize: function(options) {
        this.options = {
          method:       'post',
          asynchronous: true,
          contentType:  'application/x-www-form-urlencoded',
          encoding:     'UTF-8',
          parameters:   '',
          evalJSON:     true,
          evalJS:       true,
          on401: function() { window.location.href="/logout.jsp"; }
        };
        Object.extend(this.options, options || { });
    
        this.options.method = this.options.method.toLowerCase();
    
        if (Object.isHash(this.options.parameters))
          this.options.parameters = this.options.parameters.toObject();
      }
    });