覆盖原型 javascript 对象

Override prototype javascript object

我在 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();
  }
});

我正在尝试添加另一个选项,但我不想修改现有的原型库,而是扩展它以便它具有我的新选项。我创建了第二个 js 文件,该文件在 prototype.js 之后加载,其中包括以下内容:

  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();
  }
});

覆盖对象中的警报永远不会被调用,但它会继续使用原始对象。我一定是遗漏了什么,或者在我尝试重新定义对象后 Class.create 正在动态地做事。

我找到了一种使用 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();
  }
}); 

你应该使用函数 http://api.prototypejs.org/ajax/Ajax/Responders/register/

Ajax.Responders.register ({
  on401: function() {
      window.location.href="/logout.jsp";
})