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 GR1000GR10003 Answers
Reset to default 7Technically, 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
版权声明:本文标题:oop - Question about object.method in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741480821a2381159.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论