Can anyone, please explain in simple words why JavaScript expression
123.unexistingProperty;
throws an error, while
var v = 123;
v.unexistingProperty;
(123).unexistingProperty;
true.unexistingProperty;
"".unexistingProperty;
[].unexistingProperty;
{}.unexistingProperty;
do not?
Is this something to do with prototyping or just some rationale of the language?
P.S. Not just hypothetical, this comes up as a question when implementing eval() on dynamically generated code.
1 Answer 1
Is this something to do with prototyping
No, the reason is that Javascript doesn't allow you to access attributes directly on number literals.
For example this won't work:
123.unexistingProperty;
but this will work:
(123).unexistingProperty;
The thing is that a number can be written in the form of 10.5 Which means that the dot can't be use to access properties. For that reason, you'd have to wrap a number between parenthesis to call a property on the number.
Example:
Number.prototype.fun = function () { return "Fun" }
(100).fun()
(10.5).fun()
v.unexistingFunction();throwsUncaught TypeError: undefined is not a functionconstantwhilevis variable and v has some properties