Javascript using prototype how can I set the value

2020-05-06 16:52发布

问题:

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