开发者

Usage of toString in JavaScript [duplicate]

This question already has开发者_如何学编程 answers here: Calling member function of number literal (3 answers) Closed 9 years ago.

I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:

var level = 1;
var hex = level.toString(16);

So I run this in my browser's console to see what I get....

var level = 1;
level.toString(16);

Hey, it returns "1"... Fabuloso! Wunderbar!

Then to be cheeky, I try this to see what I get...

1.toString(16);

And I get

SyntaxError: Unexpected token ILLEGAL

What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.

Related: Stack Overflow question Why don't number literals have access to Number methods?.


It's just a language grammar limitation.

Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:

1.
toString
(
)

And that's an illegal sequence of tokens. It's object method, instead of object . method.

In the working versions in @Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:

1.0.toString()

or

1..toString()

since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.


You need 1..toString or (1).toString to get the number literal


level is a variable (and thus an object).

1 is a literal. They are not objects and the interpreter thinks about them completely differently.

http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#4

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜