Question

I'm trying following JavaScript example.

function A() {};

A.prototype.x = new Number(10);

var a = new A();

console.log(a.x);

In Firefox, its printing value as 10, but in Chrome or Node.js its printing as {}.

But when change the second line like below, then it prints 10 in chrome also

A.prototype.x = 10;

Can someone explain me the reason why new Number(10) is not working in chrome.

Was it helpful?

Solution

It's because you're making a Number wrapper object instead of a primitive, and that's Chrome's chosen representation. (Console representations are not always the same. There's no standard.)

The actual number 10 is stored in an internal property called [[PrimitiveValue]], so it's not directly exposed.

To get its [[PrimitiveValue]], you can use the .valueOf() method.

console.log(a.x.valueOf()); // 10

15.7.2.1 new Number ( [ value ] )

The [[Prototype]] internal property of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1).

The [[Class]] internal property of the newly constructed object is set to "Number".

The [[PrimitiveValue]] internal property of the newly constructed object is set to ToNumber(value) if value was supplied, else to +0.

The [[Extensible]] internal property of the newly constructed object is set to true.

OTHER TIPS

new Number(...) creates a boxed Number instance, which is not the same as a number primitive.
Chrome's console displays that as an object.

If you write console.log(new Number(10)), you'll see the same output.

If you change your code to use a primitive (A.prototype.x = 10), it will show 10.

Because Number is an object. console.log(a.x.valueOf()); or console.log(a.x.toString()); will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top