JQuery.ajax()制作设置对象的副本? [英] JQuery.ajax() makes a copy of the settings object?
问题描述
JQuery.ajax()接受设置
参数。 success
或错误
(例如)的函数在此对象的上下文中运行。
JQuery.ajax() accepts a settings
argument. The functions for success
or error
(for example) run in the context of this object.
var arr = [];
var a = {
url : '/',
arbiteraryProperty: 'yeah!',
complete:function () {
console.dir(arr[0]);
}
};
arr.push( a );
$.ajax( a );
运行命令,然后打印arr的第一个元素的属性(即a),如下所示:
runs the command and then prints the attributes of the first element of arr (which is a) as follows:
arbiteraryProperty : "yeah!"
url : "/"
complete : function()
现在问题是上面的完整
函数中的这个
关键字实际上并不是指设置
对象。这很有趣,因为似乎JQuery正在复制设置
对象。
Now the problem is that the this
keyword inside the above complete
function is not actually referring to the settings
object. It is interesting because it seems JQuery is making a copy of the settings
object.
var arr = [];
var a = {
url : '/',
arbiteraryProperty: 'yeah!',
complete:function () {
console.log(this.arbiteraryProperty );
//this prints 'yeah!'
this.arbiteraryProperty = 'nope!';
console.log( this.arbiteraryProperty );
//this prints 'nope!' so the value of the attribute in this is changed
console.log( a.arbiteraryProperty );
//this prints 'yeah!' ie. the value originally existed in the settings object
}
};
arr.push( a );
$.ajax( a );
问题是:JQuery真的创建了设置对象的副本吗?如果是,我怎么强迫它使用我的对象?
The question is: does JQuery really create a duplicate copy of the setting object? And if yes, how can I force it to use my object?
我有一个应用程序,我需要将这些对象保存在队列中并期望它们在更新时更新他们跑。我想一个替代方法是使用 $。ajax()
的 context
设置。但是,此功能的此行为(制作设置对象的副本)未记录。或者我错过了它?
I have an application where I need to save these objects in a queue and expect them to be updated when they run. I guess one alternative is to use the context
settings for the $.ajax()
. However this behavior of this function (making a copy of the settings object) wasn't documented. Or I missed it?
推荐答案
是的,当你调用 jQuery.ajax时,jQuery会创建一个新的选项对象()
。结果是您传递的设置对象和全局 jQuery.ajaxSettings
对象的组合,以便您拥有正确的默认值以及您在全局设置的任何设置,甚至当你没有在传递的对象中明确设置它们时。
Yes, jQuery creates a new options object when you call jQuery.ajax()
. The result is a combination of the settings object you passed and the global jQuery.ajaxSettings
object, so that you have the correct default values and any settings you've set globally, even when you don't explicitly set them in the object passed.
这可以在源代码:
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
通常使用 context
属性为回调函数中的 this
指定不同的值,所以:
Generally you use the context
property to specify a different value for this
inside the callback functions, so:
options = {
url: '/',
...,
context: a
}
但是,你的情况下的循环引用( a
在其中一个属性中引用自身)如果合并执行深层复制,可能会导致问题。
However, the circular reference in your case (a
referring to itself in one of its properties) may cause issues if the merge does a deep copy.
这篇关于JQuery.ajax()制作设置对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!