2017-04-12 135 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(); 
    } 
});