Number () vs new Number ()?

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

I would expect this to be an object anyway. I just messed around and I added the .helloWorld() method for the Number prototype, and I was able to access it on m no matter which method I used to create it.

What is the difference here? What do I do differently between writing Number() and new Number() ? Why is one object and the other is Number ?

+8
javascript object prototype
source share
2 answers

Number() itself returns a numeric primitive. When you call new Number() , you get a new instance of the object that represents Number ( corresponding to the ES5 specification ).

When you call a property in a primitive, the primitive is automatically placed in a window (for example, in Java) into an instance of this object, which allows you to call helloWorld() on an 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 will see that the latter works while the first does not work; in the first, Number autoboxing to the number, and the bar method (object) is added to it. When you call x.bar() , you create a new number with an automatic number that bar does not exist.

In the latter case, you add the bar method to the Number instance, which behaves like any other instance of the object, and therefore it is preserved throughout the entire life cycle of the object.

+4
source share

Here is how it is implemented. This particular constructor function, when called without new returns a primitive number. When called with new , it returns a wrapped object.

You can access the prototype methods / properties on primitives, because behind the scenes JavaScript converts them into objects, calls the prototype method, and then deletes a copy of the object. This allows you to do things like:

 var myString = "foo"; console.log( myString.length ); //=> 3 console.log( typeof myString ); //=> "string" 

An object copy of the primitive is obtained in line 2, the length property of the object is checked, and then a copy of the object is discarded. myString remains as a string primitive.

+3
source share

All Articles