Question about object.method in JavaScript

大憨熊 提交于 2020-01-03 15:36:07

问题


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


回答1:


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"



回答2:


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



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


来源:https://stackoverflow.com/questions/369424/question-about-object-method-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!