David
David

Reputation: 23

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

Can this be done? If so, how?

Upvotes: 0

Views: 333

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074999

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

Upvotes: 0

croxmeister
croxmeister

Reputation: 26

Essentially you cant, Numbers, Booleans and Strings are immutable

Upvotes: 0

sahbeewah
sahbeewah

Reputation: 2690

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

Upvotes: 1

Related Questions