0

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,

2
  • Because it's immutable, i'm not sure it makes sense to extend a primitive (which is not recommended anyways). I would instead use Math.max(X, N) or wrap this into your own class that allows overwrite of current value. Commented Jun 24, 2017 at 21:53
  • @Danosaure Thanks for the comment. Actually, the function that I mention in the question is just an example to simplify illustration of the problem. Commented Jun 25, 2017 at 2:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.