Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top