Javascript using prototype how can I set the value of “this” for a number?

China☆狼群 提交于 2019-12-20 05:40:05

问题


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

Can this be done? If so, how?


回答1:


Essentially you cant, Numbers, Booleans and Strings are immutable




回答2:


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



回答3:


JavaScript has both number primitives and Number objects. Number primitives are immutable (like all primitives in JavaScript). The numeric value of a Number object is also immutable. So your add method can only return the updated value. 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).



来源:https://stackoverflow.com/questions/26130463/javascript-using-prototype-how-can-i-set-the-value-of-this-for-a-number

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