Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - Object and primitive type equality

I know that identical objects are not equal, i.e:

var obj = { name: "Value" };
var obj2 = { name: "Value" };

console.log("obj equals obj2: " + (obj === obj2)); //evaluates to false

Yet primitive types are:

var str = "string1";
var str2 = "string1";

console.log("str equals str2: " + (str === str2)); //evaluates to true

My question is why. Why are objects and primitives treated differently? If an object is nothing but an empty container, with only the attributes you specify to put in the container, why wouldn't the container's identical attributes evaluate to be the same? I looked around for this answer on SO and elsewhere, but didn't find an answer.

Is a JS object treated as something different in the DOM than a primitive type?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This seems to really be a question about === so let's look at the Strict Equality Comparison Algorithm, in which point 7 says

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

So what does it mean to be "the same object"? It means they don't just look like eachother, but are at the same place in memory too. This means that the only time when an Object is === to an Object is when they're the same thing.

var a = {},
    b = {}, // identical to `a`
    c = a;  // same as `a`
a === b; // false
a === c; // true
b === c; // false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...