Milk3dfx
Milk3dfx

Reputation: 667

Assign new value of Number in Number method

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

Answers (2)

Oriol
Oriol

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

brk
brk

Reputation: 50326

Not sure if this will help you or not. But javascript function currying can be useful . For example

function add(x){
  return function(o){
    return x+o;
   }
}
var a = add(4)(6);
document.getElementById('updateValue').textContent=a

WORKING

Upvotes: 0

Related Questions