我想創建一個ajax對象的原型。JQuery原型功能
我已經創建了以下功能:
$.extend({
ajax_prototype : function(parammeters){
instance = this;
instance.cache = false;
instance.crossDomain = false;
instance.dataType = 'json';
instance.timeout = 30000;
instance.error = default_error_function;
$.each(parammeters,function(key,value){
instance[key] = value;
});
},
set_ajax_action : function(template,action,func,def){
template[action] = func;
}
});
ajax_prototype
是對象的構造函數。
設置一些默認設置,並根據需要設置一些默認設置。
set_ajax_action
設置要在每個事件上執行的函數。
當我創建這樣一個對象:
temp1 = new $.ajax_prototype({
'type' : 'post',
'url' : 'controller.php',
});
我得到這個對象:
Object { cache: false, crossDomain: false, dataType: "json", timeout: 30000, error: default_error_function(), type: "post", url: "controller.php", success: function() }
但之後我用這個:
$.set_ajax_action(temp1,'error',function(){console.log();});
的對象變成這樣:
Object { cache: false, crossDomain: false, dataType: "json", timeout: 30000, error: function(), type: "post", url: "controller.php", success: function() }
基本上它們的區別在於設置錯誤功能的方式。這兩個對象工作良好。
但我想使原型創建第二種形式的對象。
有人可以解釋爲什麼兩個對象的差異以及如何解決我的問題?
編輯1
我還可以創建第二個對象,即使我從我的原型刪除錯誤屬性並調用$ .set_ajax_action(...)。
我的問題是爲什麼有不同的功能演示文稿控制檯。
我知道我的問題是微不足道的,無論哪種方式結果都是一樣的,但我想知道它是如何工作的。
順便說一句,即使我設置錯誤屬性是這樣的:
instance.error = function(){ ... };
結果將是:
Object { cache: false, ifModified: false, processData: true, crossDomain: false, dataType: "json", timeout: 30000, error: .ajax_prototype/instance.error(), url: "test" }
你爲什麼使用jQuery.extend?你沒有合併任何對象。 – Ozan
@Ozan無明顯原因。我可以使用普通函數。結果是一樣的。 –
找到你的錯誤函數的定義,像'function default_error_function(){...}',並用'var default_error_function = function(){...}'代替它。它會做你想要的嗎? –