Hello a new noob on jQuery here and I was wondering if jQuery objects are immutable. For example:
var obj1 = $("<tag></tag>");
var obj2 = obj1.append("something");
Will obj1 and obj2 be the same meaning obj2 will reference obj1?
UPDATE:
The above example kind of scratches the surface of what i want to know, a more accurate question is : If i chain function from the jQuery api will they return the same object or a new one (as the case with strings in Java)?
Source: Tips4all
Both obj1 and obj2 will be a reference to the jQuery object containing the <tag></tag> element, yes.
ReplyDeleteIf you want to keep a reference to the second element, you could use .appendTo() instead:
var obj1 = $("<p>foo</p>"),
obj2 = $("<span>bar</span>").appendTo(obj1);
Yes, it obj2 will reference obj1. What it basically does is append whatever given to obj1 and returns the reference.
ReplyDeleteYou may try seeing at console that obj1 and obj2 having the text "something"
console.log(obj1);
console.log(obj2);
Assuming I've understood your question, yes, obj2 will be a reference to the object stored in obj1. If you do something to obj2:
ReplyDeleteobj2.attr("id", "example");
You will see the changes in obj1:
console.log(obj1) //Will show <tag id="example">something</tag>
You can confirm this further by testing the two objects for equality:
console.log(obj1 == obj2) //true
http://jsfiddle.net/rLg9S/
ReplyDeleteBoth object return the same element so yes.
You can use $.clone() if you need copy of the object.
ReplyDeletevar obj2 = obj1.clone().append("something");
var obj1 = $("<p></p>");
ReplyDeletevar obj2 = obj1.append("something"); // in this is you just assign the `obj1` object to `obj2`
like:
var x = 5;
var y = x; //here, both x and y are 5
So, obj1 and obj2 will refer the same thing
proof:
console.log(obj1 === obj2);
If a function changes which elements are in a selection, then yes, there will be a new object created.
ReplyDeleteFor example:
var link = $('#myLink'),
span = link.find('span');
link is a different object to span. However, the original object is not actually lost. You can go back to it very easily with the end method, which basically rolls back a manipulation operation.
$('#myLink')
.find('span') // get the span elements
.css('color', '#fff') // modify them
.end() // go back to the original selection
.css('font-size', '24px'); // modify that
So if you had a very large number of chained selection calls that didn't use end, you could end up with a very large object (because there would be a chain of objects that referenced the object that made them). This would be incredibly awkward design, however, so it's unlikely that you're doing that, while Javascript's garbage collection should generally mean that objects you've finished with don't hang around in memory.