Reputation: 667
My goal is to add method to Number object which will change the value of number. Like this
var a = 10;
a.add(5);
console.log(a); // Return 15
It is possible to do, or the only way is
Number.prototype.add = function(n) { return this.valueOf() + n; }
var a = 10;
a = a.add(5);
Thank you
Upvotes: 1
Views: 157
Reputation: 288500
The problem is that in JS, primitive values are immutable.
Theoretically, it would be possible to use a number object and alter its [[NumberData]]
internal slot. However, ECMAScript provides no way to do that.
Instead, consider returning an object which, when coerced into a number with valueOf
, returns the desired number, e.g.
function MyNumber(n) {
this.number = n;
}
MyNumber.prototype.add = function(n) {
this.number += n; return this;
};
MyNumber.prototype.valueOf = function() {
return this.number;
};
var n = new MyNumber(10);
n.add(5);
n + 0; // 15
Upvotes: 6