我的理解:在 Javascript 中,对象和数组作为引用而不是函数参数的值传递。 jQuery 组是一个对象,因此应作为引用传递。
但是我在下面的测试脚本中发现发生了一些奇怪的事情;除非包裹在另一个对象中,否则 jQuery 组的行为就像一个值而不是一个引用......任何人都可以解释这一点吗?
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script>
function test(arg){
arg = arg.add($('<span/>'))
console.log(arg);
};
ele = $('<div/>');
test(ele); // div + span in the group as expected
console.log(ele); // only the div - the 'arg' param in function was a copy
function test2(arg){
arg.a = arg.a.add($('<span/>'));
console.log(arg.a);
};
obj = {a:ele};
test2(obj); // div + span in the group as expected
console.log(obj.a); // both in the group - arg acted like a reference!
</script>
</body>
</html>
最佳答案
这是 .add()
的一个“特征”方法。它不修改原始 jQuery 对象,而是返回一个具有附加值的新对象。
鉴于您的第一个示例,您需要返回 arg
变量并覆盖 ele
.
function test(arg){
arg = arg.add($('<span/>'))
console.log(arg);
return arg; // return the new jQuery object stored in "arg"
};
ele = $('<div/>');
ele = test(ele); // overwrite the original "ele" with the returned value
console.log(ele);
编辑:再举一个例子,使用您的代码,但带有 .push()
它修改了原始对象,您将在 ele
中看到更新的正确值.
function test(arg){
arg = arg.push($('<span/>')[0])
console.log(arg); // Because .push() is being used, "arg" will reference
// the new length of the array.
};
ele = $('<div/>');
test(ele);
console.log(ele); // Will reference jQuery object with both elements
编辑:最后一个插图。因为.add()
返回一个新对象,您可以像这样更新两个变量以指向相同的值:
ele = arg = arg.add($('<span/>'));
现在代替 ele
引用原文,和arg
引用创建的新对象,两个变量都持有对内存中同一对象的引用。
关于javascript - 作为参数传递给函数的 jQuery 对象是值副本而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3709753/