views:

434

answers:

3

This is a follow-up question to this one.

Take a look at these two examples:

var number1 = new Number(3.123);
number1 = number1.toFixed(2); 
alert(number1);

var number2 = 3.123;
number2 = number2.toFixed(2);
alert(number2);

I realize they both end up with the same value, but is it correct thinking to refer to a method of a primitive value? (In other words, 3.123.method as opposed to object.method?)

+3  A: 

Technically, no. You can treat it like it is a method of the primative value, because number2 is will be converted to a Number object, then toFixed is gets called on that object.

The same thing happens when you call methods on strings.

To illustrate what's happening, you can run this code:

Object.prototype.type = function() { return typeof this; }

var string = "a string";
var number = 42;

alert(typeof string); // string
alert(string.type()); // object

alert(typeof number); // number
alert(number.type()); // object
Matthew Crumley
+3  A: 

In JavaScript, everything is an object, even functions and integers. It is perfectly OK to think of methods on numbers and strings. For example:

>>> (3.123).toString()
"3.123"
Steven Huwig
Thanks, but why is it that typeof number2 indicates it's a string and not an object?
toFixed() converts to a string.
Steven Huwig
Sorry, I meant before toFixed is applied, in which case its typeof is number and not object, which it technically is.
An object can return true for many different instanceof parameters, but it can only have a single type.
Steven Huwig
+1  A: 

Calling a method on a literal value or variable initialized with a primitive value has the same effect as first coercing the value to an Object of appropriate type and then calling the method on it. The following experiment is better than trying to explain this in words:

Object.prototype.getPrototype = function() { return "Object"; };
Number.prototype.getPrototype = function() { return "Number"; };

function test(v) {
    alert("proto: " + v.getPrototype()
     + ", type: " + typeof v
     + ", is a Number: " + (v instanceof Number)
     + ", is an Object: " + (v instanceof Object));
}

// proto: Number, type: number, is a Number: false, is an Object: false
test(42);

// proto: Number, type: number, is a Number: false, is an Object: false
test(Number(42));

// proto: Number, type: object, is a Number: true, is an Object: true
test(Object(42));

// proto: Number, type: object, is a Number: true, is an Object: true
test(new Number(42));
Ates Goral