How to extend Number in TypeScript by adding a function similar to ++

Viewed 343

I would like to extend Number with a plusPlus2 function that will increment the number by 2.

The problem is that I don't know how to assign the result back to the number in the extension function. Something like:

Number.prototype.plusPlus2 = function() {
    this = this + 2;
}

And the usage would be:

x = 1;
x.plusPlus2(); // expect x to be 3
3 Answers

Primitives (numbers, strings, booleans) are immutable in javascript.

So anytime you change a primitive, you need to assign it to another variable (or even reassign it to itself).

That being said, you cannot do what you propose, you need to return a new value, containing the value you want, let's say:

Number.prototype.plusplus2 = function() { 
    return this + 2;
}

And then reassign it:

let x = 5;
x = x.plusplus2();

Then, you may be wondering: how x++ works?

And the answer is, x++ is a syntax sugar for x = x + 1, meaning that, in fact, you are not changing x, but instead, adding 1 to x and reassigning it to itself.

You cannot. That has various reasons:

1) this is read only, as you don't expect it to change during the execution of a method.

2) What you access with this is a Number object that wraps the primitive number. It gets thrown away after the call. So even if you could change the internal value property containing the number, the value of x won't change.

 Number.prototype.example = function() { this.stuff = "you see" };
 let x = 1; // primitive
 x.example(); // wrapped object
 // wrapped object gets thrown away
 console.log(x.stuff); // undefined, another wrapped object

3) Numbers are immutable and primitive. You can write a new number into x, but you can't turn all 1s into 3s.


You could create a new number, but then you have the problem that you have to write that number into x.

 Number.prototype.plus2 = function() { return this + 2 };
 let x = 1;
 x = x.plus2();
Number.prototype.plus2 = function() {
    return this + 2
}

let a = 2
console.log(a.plus2())
Related