Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery object are immutable?

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)?

like image 700
Daniel Avatar asked Nov 16 '11 09:11

Daniel


People also ask

Are objects immutable in JavaScript?

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.

Why is JavaScript immutable?

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.

What is mutable vs immutable?

Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.

How can we make an object immutable in JavaScript?

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.


1 Answers

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);
like image 132
Mathias Bynens Avatar answered Oct 01 '22 08:10

Mathias Bynens