Skip to content Skip to sidebar Skip to footer

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? You'll notice rad.add(10) returns the number contained in th

Solution 1:

Number.prototype.add = function(num){
  var newVal = this.valueOf() + num;
  this.valueOf(newVal);
  return newVal;
}

var rad = newNumber(4001.23);
document.write(rad.add(10) + '<br/>' + rad);

Solution 2:

Essentially you cant, Numbers, Booleans and Strings are immutable

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

Post a Comment for "Javascript Using Prototype How Can I Set The Value Of "this" For A Number?"