Here's a plunk that demonstrates my question: http://plnkr.co/edit/322WB4jyCJberABbb0P0

I'm doing some testing for a different issue and I came across some unexpected behavior.

var A = function() {}
A.prototype = {
  constructor: A,
  x: 10
};

var a = new A();

document.writeln("a.x is " + a.x + "<br>");
document.writeln("a.constructor === A is " + a.constructor === A + "<br>");
var result = a.constructor === A;
document.writeln("a.constructor === A is " + result + "<br>");

The second writeln doesn't concatenate the strings with the value and it writes "false". The third writeln concatenates and writes as expected.

This isn't really something I'd do outside of testing, but I'd like to understand why the second writeln behaves this way.

有帮助吗?

解决方案

That's because === has a lower precedence than + - otherwise you wouldn't be able to write simple equations like a + b === c + d!

So just use parentheses around (a.constructor === A) and all will be well.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top