簡體   English   中英

覆蓋原型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";
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM