Peregring-lk Peregring-lk - 11 days ago 6
Javascript Question

Assigning a function to a member of a number, why is that not a failure?

From my Chrome interpreter:

a = 3; // OK, of course.
a.f = function() { return 4; }; // OK. To a number? Ok
a; // Prints 3
a.f(); // f is not a function.
a.f; // Undefined


Of course,
a
is not an object, and I cannot assign new members to something that isn't an object. But, why does the interpreter swallows the
a.f
assignment if after that the method or the member doesn't even exist?

Answer

If you look at 8.7.2 of the ECMA 5.1, you will notice this note at the bottom:

The object that may be created in step 1 is not accessible outside of the above method. An implementation might choose to avoid the actual creation of that transient object. The only situations where such an actual property assignment that uses this internal method can have visible effect are when it either invokes an accessor function or is in violation of a Throw predicated error check. When Throw is true any property assignment that would create a new property on the transient object throws an error.

Step 1 is Let O be ToObject(base).

If you look at the ToObject() method in 9.9, you will find these two rows in the table:

  • Number

Create a new Number object whose [[PrimitiveValue]] internal property is set to the value of the argument. See 15.7 for a description of Number objects.

  • Object

The result is the input argument (no conversion).


So it looks like when you attempt to set the function on the number, it is actually happening (although as a noop), it just becomes unaccessible after the assignment, due to the assignment happening on an internal transient object. When you do it on a regular object, it returns the actual object, so the assignment makes sense.

Comments