Question

(3).constructor is Number, but "constructor" in (3) is TypeError, why?

Was it helpful?

Solution

With using the property accessor, the number 3 is turned into an object of Number. And an object of that type has a constructor and thus an constructor property.

But as ChaosPandion already pointed out, the in operator requires the right expression to yield an object but 3 is not an object but a plain number literal.

OTHER TIPS

The specification for the in operator explains this. Specifically, see step 5 of semantic evaluation.

11.8.7 The in operator

The production RelationalExpression : RelationalExpression in ShiftExpression is evaluated as follows:

  1. Let lref be the result of evaluating RelationalExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating ShiftExpression.
  4. Let rval be GetValue(rref).
  5. If Type(rval) is not Object, throw a TypeError exception.
  6. Return the result of calling the [[HasProperty]] internal method of rval with argument ToString(lval).

The reason (3).constructor works is a a bit more challenging to understand but essentially when you use the dot operator on a reference with a primitive base it gets lifted into an object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top