javascript - 作为参数传递给函数的 jQuery 对象是值副本而不是引用?

标签 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>

最佳答案

这是 .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/

相关文章:

javascript - 在参数中传递函数,在负载上运行

javascript - 客户端脚本 VS 服务器端代码

javascript - 如何在加载时使用 javascript 设置高度

JavaScript 对象实例委托(delegate)/转发

javascript - 是否可以使用客户端 JavaScript 实现类似 Firebug "inspect element"DOM 元素荧光笔?

javascript - JQuery ,each() 和 UI.sortable()

javascript - 如何检查 div 是否具有液体/自动高度?

javascript - 如何防止通过退出键关闭弹出窗口

jquery - 文本框内的可移除标签

jquery - 如何在html5中地址栏左对齐