Given
var o = {};
var p = new Object();
p === o; //false
o.__proto__===p.__proto__ // true
why is this false?
please tell me the immediate reason to return false??
Given
var o = {};
var p = new Object();
p === o; //false
o.__proto__===p.__proto__ // true
why is this false?
please tell me the immediate reason to return false??
The two objects contain the same thing (i.e. nothing) but they are not the same object.
Javascript's object equality test requires that the two parameters refer to the exact same object.
The ===
for objects is defined as:
11.9.6 The Strict Equality Comparison Algorithm
The comparison
x === y
, wherex
andy
are values, producestrue
orfalse
. Such a comparison is performed as follows:...
7. Return
true
ifx
andy
refer to the same object. Otherwise, returnfalse
.
In this case, although both are empty objects, they are created separately and hence do not refer to the same object.
As a side note, both constructions do the same thing; but it is common practice to use {}
.
JavaScript strict comparison for objects tests whether two expressions refer to the same objects (and so does the normal equals operator).
You create the first object using object literal {}
which creates a new object with no properties.
You create the second object by calling Object
constructor as a function. According to section 15.2.1.1 of ECMAScript Language Specification this also creates a new object just as if new Object()
was used.
Thus you create two objects, store their references under p
and o
and check whether p
and o
refer to the same object. They don't.
Every time you create an object, the result has its own, distinct identity. So even though they are both "empty", they are not the same thing. Hence the ===
comparison yields false
.
Using the ===
, the result will show if items on both side is the "Same Instance"
If you like to comparing two item are same type, you should use:
var o1 = {};
var o2 = new Object();
alert( typeof(o1) === typeof(o2));
and if you like to tell if the two object is considered equal (in properties and values), you should try underscore.js library and use the isEqual
function.
Is this homework?
In that case, I will only give you some hints: - Think about what the first two lines do. Do o and p refer to the same object after those two lines? - Look up exactly what === does. Does it compare two objects to see if their structure are the same? Or does it compare the objects based on their identity?
Object is an unordered collection of properties each of which contains a primitive value, object, or function. So, each object has properties and prototypes and there's no any sense to compare the one.