JavaScript中对象上的运算符==和===

JavaScript中对象上的运算符==和===,javascript,Javascript,我非常清楚上下文中的两个运算符与基本类型number、string、boolean、null和undefined的区别。我是说那些东西 0 == false // true 0 === false // false, because they are of a different type 1 == "1" // true, auto type coercion 1 === "1" // false, because they are of a different type

我非常清楚上下文中的两个运算符与基本类型number、string、boolean、null和undefined的区别。我是说那些东西

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, auto type coercion
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
以片段为例

        var str3 = new String("abc");
        var str4 = new String("abc");

        // false as 2 different objects, referential equality just like in java
        alert(str3 == str4);


        var str5 = new String("abc");
        var str6 = str5;
        alert(str6 == str5);        // true, as pointing to the same object
对于str5和str6,它们将进行真实的比较。当然,使用严格比较===将产生相同的结果,因为它们是相同的值和类型;事实上,他们是同一个对象

现在考虑,

function Person(name) {
  this.name = name;
}

// the function person has a prototype property
// we can add properties to this function prototype
Person.prototype.kind = ‘person’

// when we create a new object using new
var zack = new Person(‘Zack’);

// the prototype of the new object points to person.prototype
zack.__proto__ == Person.prototype //=> true

zack.__proto__ === Person.prototype //=> false
我发现自己对最后两行很困惑:

zack.__proto__ == Person.prototype //=> true
zack.__proto__ === Person.prototype //=> false
根据我的理解,zack.\uuuu proto\uuuuu和Person.prototype指向同一对象,指向内存中的同一位置,因此是正确的


如果是这样的话,为什么zack.\uu proto\uuuuuuuuu==Person.prototype为false呢?因为zack.\uu proto\uuuuuuuuuuu和Person.prototype的类型都是object,而且由于它们指向内存中的同一位置,所以它们必须具有相同的值。

如果两个操作数具有相同的类型,则使用==或===也无所谓:

抽象等式比较算法

比较x==y,其中x和y是值,生成真或假 错误的这样的比较如下所示:

如果Typex与Typey相同,则 如果Typex未定义,则返回true。 如果Typex为Null,则返回true。 如果Typex是数字,那么 如果x为NaN,则返回false。 如果y为NaN,则返回false。 如果x与y的数值相同,则返回true。 如果x为+0,y为−0,返回true。 如果x是−0且y为+0,返回true。 返回false。 如果Typex是String,那么如果x和y是相同长度的字符序列,并且在 相应的位置。否则,返回false。 如果Typex为布尔值,则如果x和y均为真或均为假,则返回真。否则,返回false。 如果x和y引用同一对象,则返回true。否则,返回false。 [...] 严格等式比较算法

比较x===y,其中x和y是值,生成真或假 错误的这样的比较如下所示:

如果Typex与Typey不同,则返回false。 如果Typex未定义,则返回true。 如果Typex为Null,则返回true。 如果Typex是数字,那么 如果x为NaN,则返回false。 如果y为NaN,则返回false。 如果x与y的数值相同,则返回true。 如果x为+0,y为−0,返回true。 如果x是−0且y为+0,返回true。 返回false。 如果Typex是String,那么如果x和y是相同长度的字符序列,并且在 相应职位;否则,返回false。 如果Typex是布尔值,如果x和y都为真或都为假,则返回真;否则,返回false。 如果x和y引用同一对象,则返回true。否则,返回false。 所以,

function Person(name) {
  this.name = name;
}
Person.prototype.kind = 'person';
var zack = new Person('Zack');
zack.__proto__ == Person.prototype;  // true
zack.__proto__ === Person.prototype; // true

如果你说它在Eclipse IDE中返回false,那就意味着Eclipse IDE没有遵循ECMAScript标准。

Foo是在哪里定义的?@elclanrs:大家很抱歉。已编辑。@ShirgillAnsari您应该使用“或”代替。我无法重现您的问题。正如所料,我得到了正确的答案。_proto__属性是,所以无论如何都不应该使用它。当你说在这两种情况下都能反映真实情况时,我就用谷歌浏览器进行了反复检查。非常感谢。