5

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?)

Community
  • 1
  • 1

3 Answers3

7

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
  • 101,441
  • 24
  • 103
  • 129
4

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
  • 20,015
  • 9
  • 55
  • 79
3

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
  • 137,716
  • 26
  • 137
  • 190