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?
PS Not just hypothetical, this comes up as a question when implementing eval()
on dynamically generated code.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.