简体   繁体   English

Chrome console.log矛盾

[英]Chrome console.log contradictions

I have a simple class 我有一堂简单的课

function TrueNinja() {
   this.vanish = function() { return this; };
}

creating a new object from this 由此创建一个新对象

var someNinja = new TrueNinja();

when i do the following in chrome i get two different outputs 当我在Chrome中执行以下操作时,我得到两个不同的输出

console.log(someNinja instanceof TrueNinja); // i get true
console.log("someNinja: " + someNinja instanceof TrueNinja); //i get false

WHY?? 为什么?? :-( the first statement is the correct output since someNinja IS an instance of TrueNinja... but why do i get false in the next statement? :-(第一条语句是正确的输出,因为someNinja是TrueNinja的一个实例...但是为什么在下一条语句中我会得到假?

这是由于运算符的优先级, +instanceof之前先求值。

You need to give like this: 您需要这样给:

"someNinja: " + (someNinja instanceof TrueNinja);

The reason is, the whole "someNinja: " + someNinja is compared with TrueNinja . 原因是,整个"someNinja: " + someNinjaTrueNinja进行了TrueNinja

So, this way, it compares, "someNinja: " + someNinja With the TrueNinja , where, the former is string and latter is TrueNinja . 因此,通过这种方式,它与"someNinja: " + someNinjaTrueNinjaTrueNinja ,其中,前者是string而后者是TrueNinja Hope it is clear! 希望清楚! :) :)

The actual reason is because of Operator Precedence, where + comes before instanceof . 实际原因是由于运算符优先级,其中+出现在instanceof之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM