vitaly-t
vitaly-t

Reputation: 25840

JavaScript prototyping basics

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.

Upvotes: 2

Views: 41

Answers (1)

Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

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()

Upvotes: 4

Related Questions