Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (3).constructor is valid while "constructor" in (3) is not valid?

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

like image 854
ithinc Avatar asked Oct 24 '25 16:10

ithinc


2 Answers

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.

like image 92
Gumbo Avatar answered Oct 26 '25 05:10

Gumbo


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.

like image 28
ChaosPandion Avatar answered Oct 26 '25 05:10

ChaosPandion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!