My understanding: in Javascript objects and arrays get passed as references not values for function arguments. A jQuery group is an object and hence should be passed as reference.
However I’m finding in the test script below that something strange is going on; the jQuery group is behaving like a value not a reference unless wrapped in another object … can anyone explain this?
<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>
This is a “feature” of the
.add()method. It does not modify the original jQuery object, but rather returns a new object with the added value.Given your first example, you would need to return the
argvariable and overwriteele.EDIT: To give another illustration, using your code, but with
.push()which modifies the original object, you will see the correct value updated inele.EDIT: Once last illustration. Because
.add()returns a new object, you could update both variables to point to the same value like this:Now instead of
elereferencing the original, andargreferencing the new Object that was created, both variables hold a reference to the same Object in memory.