JavaScript object comparison
Why do the last ==
and ===
operators return true here?
var object1 = {value: 10};
var object2 = object1;
alert(object1开发者_Go百科 == object2); // result makes sense
object2.otherValue = 15;
alert(object1 == object2); // doesn't make intuitive sense to me
alert(object1 === object2); // neither does this
On the third line, you set object1 and object2 to reference the same object. There is only one object that exists throughout the entirety of your program.
Thus the assignment on line 5 changes the value of that single object; in other words, object1.otherValue === 15
is true after that line is run, even though you changed the object through a different reference to it.
Hence why the equality checks are still true, because object1 is object2, and of course it's equal to itself.
When you assign an object like this:
var object2 = object1;
you're actually assigning a reference to the object. There's only one object, now with two references to it. Any changes are visible through either reference, because they're referring to the same thing.
If you want to create a copy, or clone, of the original object, JavaScript doesn't have a built-in way to do that. (And writing your own isn't trivial, and has been discussed on Stack Overflow many times: https://stackoverflow.com/search?q=javascript+clone+object)
When you do var object2 = object1;
, you're not creating a copy of object1, you're creating a reference to it. object2 now refers to the same piece of memory as object1.
Therefore any changes you make in either one will be reflected in the other.
精彩评论