IN javascript,why {}!==Object()?

别说谁变了你拦得住时间么 提交于 2020-01-04 05:54:22

问题


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


回答1:


The === for objects is defined as:

11.9.6 The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

...

7. Return true if x and y refer to the same object. Otherwise, return false.

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 {}.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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.




回答6:


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?




回答7:


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.



来源:https://stackoverflow.com/questions/8699816/in-javascript-why-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!