My question is about the Mozilla developer page: typeof operator

In the example chapter, whenever a comparison of the following form is done they comment it:

typeof Number(1) === 'number'; // but never use this form!

Although they never explain why. It's easy to see why it's a silly way of going about type-checking, but I'm curious as to the reason why they went out of their way to make that comment multiple times.

Any clues are welcome.

Note: Is it because Number() is a constructor called without the new operator? (my first guess)

Ps: Code examples were tested in Firefox's console version 27.0

有帮助吗?

解决方案 2

It is because of the lack of new. Writing new Number(1) creates a Number object with the value 1. This is seldom needed. However, Number(1) does not create a Number object — instead, it just returns the number 1. This is confusing (since it visually looks like object creation) and unnecessary since you can just write 1 instead.

其他提示

They do explain why. On that same page, (a little bit past what you copied), it says

typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1) === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object';  // this is confusing. Don't use!

Notice how the new keyword is there. In your example, there is no new keyword. Kind of hard to spot, isn't it? So what they're trying to say is that since one's type is number and the other's type is object but the two look so similar, it's can be confusing what you mean.

Many problems can arise from thinking an object is a number because it acts like a number in some ways. For example, type checking with typeof and comparisons with ===.

Although, I can see that it isn't expressed very clearly on that page.

The author(s) of that page seem to be a bit confused or intent on causing confusion.

There’s nothing wrong with that “form” except that Number(1) is redundant – it’s equivalent to 1.

Arguably, it’s confusable with new Number(x), but +x (the other common way) is kind of obscure at first glance, and there’s no chance of mixing the two up if you know to never use primitive wrappers.

Did I mention you should never use primitive wrappers?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top