Create an object similar to Number in JavaScript

How to create a new primitive or object where I can use the operators used in Number?

I want to create a new object, for example Number, with a different name, different properties and where I can use operators, i.e. 4 + 5

+4
source share
2 answers

You can override the prototype of valueOf objects to create your own primitive:

 var N = function(n) { this._value = n; } N.prototype.valueOf = function() { return this._value+1; }; console.log( new N(4) + 4 ); // 9 

See examples and more information here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/valueOf

0
source

You can use the Number object if you want it specifically for a number. If you want it for something else and use only the number as an example, you cannot do this because JavaScript does not support operator overloading.

It’s best to hide the chain by returning this to the plus function so that you can:

 var n1 = new MyNumber(1); var n2 = new MyNumber(2); var n3 = new MyNumber(3); var sum = n1.plus(n2).plus(n3); // sum: 6 

You also need to make sure MyNumber creates a new MyNumber and returns this if you do not want to change the numbers.

0
source

Source: https://habr.com/ru/post/1445475/


All Articles