Behnam Ghiaseddin
Behnam Ghiaseddin

Reputation: 302

Node.js change Number object value inside prototype

I want to add a new method to Number type, and then use it to change its own value. I write below code:

Number.prototype.maxx = function(N) {
  if (N > this.valueOf()) {
    //change this number value to N 
  }
}

var X = 5;
X.maxx(7);
console.log(X); //expect to show 7

I try something like below codes to change the value

this = N;

OR

this.valueOf(N);

OR

this.value = N; //of course number do not have any property named 'value'. but I just try it!

but none of them working.

Could you please give me some hint to do this. Thanks,

Upvotes: 0

Views: 1217

Answers (2)

SzybkiSasza
SzybkiSasza

Reputation: 1599

You cannot change primitive value of the built-in types, as it's stored in a special property (I believe it might be Symbol). Number is immutable as well.

You can still create a method that will return bigger of the two.

Upvotes: 0

gauravmuk
gauravmuk

Reputation: 1616

Number.prototype.maxx = function(N) {
  if (N > this.valueOf()) {
    return N;
  } else {
    return this.valueOf(); 
  }
}

var X = 5;
X = X.maxx(4);

One thing that I would like to highlight over here is when you call X.maxx you cannot change the value of this. Instead, you will have to re-assign the value being returned back from the method to X.

Upvotes: 1

Related Questions