I've noticed this behavior when writing my JavaScript, and I haven't been able to figure out why:
Below is some code to reproduce the behavior in question.
var o1 = {
num: 1
}
var o2 = o1;
o2.num = 2;
alert(o1.num);
Expected Result: The browser alerts 1, because I only changed a property of the o2 object, not the o1 object.
Actual Result: The browser alerts 2, because it seems o1 is equal to o2.
I'm not really sure what's going on. How can I fix the code so it alerts 1 rather that 2 (assuming that o1 hasn't changed)?
Much thanks in advance.
Because both variables reference the same object. Objects are not cloned/copied on variable assignment. You would have to do this yourself.
JavaScript behaves the same way like any (most) other OO languages in this case.
By writing var o2 = o1; you're making o1 and o2 two references to the same object. What you want to do is to clone the o1 object and to store the cloned copy in o2. Search for cloning objects in JavaScript.
Because you are setting the objects to the same reference point. You need to clone the object. here is a piece of code from http://www.thespanner.co.uk/2008/04/10/javascript-cloning-objects/ that allows for cloning of objects with prototyping.
Object.prototype.clone = function() {
return eval(uneval(this));
}
alert("test".clone());
alert((3).clone());
alert(clone.clone());
Related
It seems to be a very common thing but a bit confusing. I am stuck at 2 scenarios and trying to understand what is happening over here.
Scenario 1
let obj2 = {b:{c:{d:4}}}
let obj1 = {a:obj2['b']}
obj2['b'] =9
console.log(obj1)// --- > { a: { c: { d: 4 } } }
console.log(obj2)// --- > { b: 9 }
When I changed the value of obj2['b'] I was expecting obj1 will also change as obj1['a'] was
also referencing the same memory location but it didn't.
Scenario 2
let obj2 = {b:{c:{d:4}}}
let obj1 = {a:obj2['b']}
obj2['b']['c'] =9
console.log(obj1)// --- > { a: { c: 9 } }
console.log(obj2)// --- > { b: { c: 9 } }
When I changed the value of obj2['b']['c'] value of obj1['a']['c'] also changes because it was
referencing to the same memory location. That I understood, it is expected behavior.
I want an explanation of Scenario 1, why it didn't change the value of obj1 ?
I think some diagrams might be useful here to help show what's going on. In your first code block, after your first two lines of code execute, you have a situation which looks like this:
Notice that both keys b and a from both objects 1 & 2 store references to the same object in memory. Once line three executes, you get the following situation:
As you can see, the b key for obj2 now holds the value 9, and no longer holds a reference to the object. However, obj1 still holds a reference to the object. As a result, when you log obj1, you'll still see the c and d properties of the nested objects.
For scenario two, however, your situation is a little different. After the first two lines of code execute, you get the same diagram as shown in the first image of this answer. However, once line 3 executes, your diagram changes to be:
In this situation the keys a and b for objects 1 and 2 still store references to the same object in memory (unlike in the previous scenario). This time, the object they both point to in memory is updated so that the value at the c key is no longer a reference to an object in memory, but rather the value 9. As a result, when you log both obj1 and obj2, you see the same nested object.
The above diagrams were generated by pythontutor under the ES6 visualizer.
In Scenario 1 you created an object (obj2) that has a property b that was assigned a reference to a new object, then you created a new object (obj1) and it has a property a that is a reference to the same object that in the b property in obj2.
once you changed the b property in obj2 the object that was in there is referenced only in obj1's a property.
basically, objects are in the heap memory and you store their addresses in the properties so once you change the property to a different thing you are not deleting it you just stop referencing the object and if nothing else is referencing it the GC will delete it eventually.
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.
First I tried this example in the console:
a = b = {};
a.foo = 'bar';
console.log(b.foo);
The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.
a = b = 'foo';
a = 'bar';
console.log(b);
That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.
Why does this happen?
N.B. This example could be simplified even more with the following code:
a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);
a = 'foo';
b = a;
a = 'bar';
console.log(b);
(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a and b are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo as well since a and b point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a points to a different object now. This has no effect on what a pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object.
There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introduction to JavaScript's type system:
In JavaScript, there are two fundamentally different kinds of values: primitives and objects (and there is no thing like a 'hash').
Strings, numbers and booleans as well as null and undefined are primitives, objects are everything which can have properties. Even arrays and functions are regular objects and therefore can hold arbitrary properties. They just differ in the internal [[Class]] property (functions additionally have a property called [[Call]] and [[Construct]], but hey, that's details).
The reason that primitive values may behave like objects is because of autoboxing, but the primitives themselves can't hold any properties.
Here is an example:
var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);
This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.
Think of it like this:
var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created
You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.
In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.
here is my version of the answer:
obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"
// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"
// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory
You are setting a to point to a new string object, while b keeps pointing to the old string object.
In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.
The difference is between simple types and objects.
Anything that's an object (like an array or a function) is passed by reference.
Anything that's a simple type (like a string or a number) is copied.
I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.
I am quoting this statement from the JavaScript Definitive Guide book in section 6.1.4 Object.create(). The following statement doesn't seem clear to me.
You can pass null to create a new object that does not have a prototype, but if you do this, the newly created object will not inherit anything, not even basic methods like toString() (which means it won't work with the + operator either)
var o2 = Object.create(null) // o2 inherits no props or methods.
At this point, I was thinking "Oh Wow". It doesn't inherit any basic methods, when you set Object.create(null). So, I tried to give it a try on console to see if this was really the behavior. I ran the script that is below, and got an unexpected result.
var o2 = Object.create(null);
o2.number = 1;
console.log(o2.number.toString()); // "1"
When I ran this code, I was thinking that the .toString was not going to work. I am bit confused or may not understand how things are working here. I was wondering if anyone could clear things up for me. Any help will be appreciated, and thanks for the time for reading my problem. :)
You're calling toString on the number property, which is not the object itself. If you were to try o2.toString(), it would not work.
toString works in your example because you're running it on a number, not the object itself.
It works because it's no different than this:
var n = 1;
console.log(n.toString());
To see the results of no prototype, try this instead:
var o2 = Object.create(null);
console.log(o2.toString());
When you do ...
o2.number = 1
... you're creating a property named number and adding that property to your o2 object.
When you do ...
o2.number.toString()
... you're executing toString not on o2, but on property o2.number.
If you do...
console.log(typeof o2.number)
... you'll see that o2.number has type number, and thus has all methods associated with numbers.
If you do ...
console.log(typeof o2)
... you'll see that o2 has type object.
If you try executing o2.toString, you'll get an error and see that this object indeed doesn't have any method named toString.
Note :
In my experience, you probably don't ever want to do something like ...
var o2 = Object.create(null);
o2.number = 1;
What you probably want instead, is something like ...
var o2 = Object.create(Object.prototype);
o2.number = 1;
... which can can be written more elegantly like ...
var o2 = {
number : 1
};
There is little to no advantage with creating objects that do not inherit from Object.prototype. And if other people end up using your code, you're likely to confuse the heck out of other developers when they're trying to call eg. hasOwnProperty or toString on your object and they're getting an error (as they these methods expect to exist for any object).
According to the jQuery documentation, "Not All jQuery Objects are Created ===."
"An important detail regarding this "wrapping" behavior is that each wrapped object is unique. This is true even if the object was created with the same selector or contain references to the exact same DOM elements."
documentation
I know how to work around this but why is this the case? Is this some specific way that JavaScript behaves?
Yes. Every object in JS is unique, in that o1 === o2 will not be true unless o1 and o2 are pointers to the same object.
{ foo: 1 } === { foo: 1 }; // false
So jQuery objects simply follow this same rule:
var jq1 = $('.foo');
var jq2 = $('.foo');
jq1 === jq2; // false
The only exception is if you have variables that actually point to the same jQuery object:
var jq3 = jq1;
jq3 === jq1; // true
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.
First I tried this example in the console:
a = b = {};
a.foo = 'bar';
console.log(b.foo);
The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.
a = b = 'foo';
a = 'bar';
console.log(b);
That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.
Why does this happen?
N.B. This example could be simplified even more with the following code:
a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);
a = 'foo';
b = a;
a = 'bar';
console.log(b);
(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a and b are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo as well since a and b point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a points to a different object now. This has no effect on what a pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object.
There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introduction to JavaScript's type system:
In JavaScript, there are two fundamentally different kinds of values: primitives and objects (and there is no thing like a 'hash').
Strings, numbers and booleans as well as null and undefined are primitives, objects are everything which can have properties. Even arrays and functions are regular objects and therefore can hold arbitrary properties. They just differ in the internal [[Class]] property (functions additionally have a property called [[Call]] and [[Construct]], but hey, that's details).
The reason that primitive values may behave like objects is because of autoboxing, but the primitives themselves can't hold any properties.
Here is an example:
var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);
This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.
Think of it like this:
var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created
You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.
In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.
here is my version of the answer:
obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"
// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"
// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory
You are setting a to point to a new string object, while b keeps pointing to the old string object.
In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.
The difference is between simple types and objects.
Anything that's an object (like an array or a function) is passed by reference.
Anything that's a simple type (like a string or a number) is copied.
I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.