문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top