作为参数传递给函数的jQuery对象是值复制而不是引用?

Mac*_*Elf 6 javascript jquery

我的理解:在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>
Run Code Online (Sandbox Code Playgroud)

use*_*716 3

这是该方法的“特征” .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); 
Run Code Online (Sandbox Code Playgroud)

编辑:再举一个例子,使用您的代码,但.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
Run Code Online (Sandbox Code Playgroud)

编辑:最后一个插图。因为.add()返回一个新对象,所以您可以更新两个变量以指向相同的值,如下所示:

ele = arg = arg.add($('<span/>'));
Run Code Online (Sandbox Code Playgroud)

现在,两个变量不再ele引用原始对象,也不再arg引用创建的新对象,而是保存对内存中同一对象的引用。