[英]Javascript using prototype how can I set the value of “this” for a number?
So if we can get past the "should you?" 因此,如果我们能够克服“应该吗?” question ... does anyone know how to set the value of an integer in prototype?
问题...有人知道如何在原型中设置整数的值吗?
Number.prototype.add = function(num){ var newVal = this.valueOf() + num; this.valueOf(newVal); return newVal; } var rad = 4001.23; document.write(rad.add(10) + '<br/>' + rad);
You'll notice rad.add(10) returns the number contained in the variable "rad" plus 10, but I would really like to change the value of rad from within the prototype add function (something I know this.valueOf(newVal) does not accomplish). 您会注意到rad.add(10)返回变量“ rad”加上10所包含的数字,但是我真的很想从原型添加函数中更改rad的值(我知道这一点。value。(newVal)无法完成)。
Can this be done? 能做到吗? If so, how?
如果是这样,怎么办?
Number.prototype.add = function(num){ var newVal = this.valueOf() + num; this.valueOf(newVal); return newVal; } var rad = new Number(4001.23); document.write(rad.add(10) + '<br/>' + rad);
本质上你不能,数字,布尔值和字符串是不可变的
JavaScript has both number primitives and Number
objects. JavaScript同时具有数字基元和
Number
对象。 Number primitives are immutable (like all primitives in JavaScript). 数字基元是不可变的(就像JavaScript中的所有基元一样)。 The numeric value of a
Number
object is also immutable. Number
对象的数值也是不可变的。 So your add
method can only return the updated value. 因此,您的
add
方法只能返回更新后的值。 You can create your own number-like object, of course, with a mutable value. 当然,您可以创建一个具有可变值的数字对象。
Details about number immutability and your own number object in this other answer (didn't realize that question was a duplicate when answering it) . 关于号码不变性和您自己的号码对象的详细信息在另一个答案中 ( 回答时 并没有意识到那个问题是重复的) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.