admin管理员组

文章数量:1289971

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

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

Share Improve this question edited May 23, 2017 at 12:27 CommunityBot 11 silver badge asked Dec 15, 2008 at 19:23 GR1000GR1000
Add a ment  | 

3 Answers 3

Reset to default 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

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"

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

本文标签: oopQuestion about objectmethod in JavaScriptStack Overflow