Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number() vs new Number()? [duplicate]

I'm trying to understand the difference between writing m = Number() (which causes typeof m to evaluate as "number") vs m = new Number() (which causes typeof m to evaluate as "object").

I would have expected it to be an object either way. I was just messing around, and I added a .helloWorld() method to the Number prototype, and I was able to access it on m regardless of which method I used to instantiate it.

What's the difference here? What am I doing differently between writing Number() and new Number()? Why is one an object while the other is a number?

like image 914
temporary_user_name Avatar asked Dec 22 '13 21:12

temporary_user_name


1 Answers

Number() by itself returns a number primitive. When you call new Number() you receive a new instance of an Object which represents Number's (relevant ES5 spec).

When you call a property on a primitive, the primitive is auto-boxed (like in Java) to an instance of that object, which is what lets you call helloWorld() on either the object or number.

However, try this;

var x = Number(5);
x.bar = function (x) { alert(x); };
x.bar("hello");

var y = new Number(5);
y.bar = function (x) { alert(x); };
y.bar("hello");

You'll see the latter works whilst the former does not; in the first, the number is autoboxed to a number, and the bar method is added to it (the object). When you call x.bar() you're creating a new auto-boxed Number, which bar doesn't exist on.

In the latter, you're adding a bar method to that Number instance, which behaves like any other Object instance, and therefore it persists throughout the lifetime of the object.

like image 70
Matt Avatar answered Oct 11 '22 19:10

Matt