2017-04-12 107 views
0

我已在在prototype.js中以下內容:覆蓋原型的JavaScript對象

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

我嘗試添加另一種選擇,但我不希望修改現有的原型庫,但它延伸,使得它將有我的新選擇。我創建了prototype.js是被加載後,包括以下第二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正在動態地做事。

回答

0

我找到了一種方法,使其工作使用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(); 
    } 
});