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)?
In JavaScript Arrays and Objects are not immutable. Their values can be changed over time. Both are always passed as a reference and the vast majority of available methods mutate data in place.
Immutable. js is a library that supports an immutable data structure. It means that once created data cannot be changed. It makes maintaining immutable data structures easier and more efficient.
Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.
You can freeze (make immutable) an object using the function Object. freeze(obj) . The object passed to the freeze method will become immutable. The freeze() method also returns the same object.
Both obj1
and obj2
will be a reference to the jQuery object containing the <tag></tag>
element, yes.
If 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With