One way to make a numeric value, such as 5 "chainable," is to define a method on the corresponding prototype object, such as Number.prototype . For instance:
Number.prototype.add = function (n) { return this + n } (5).add(2)
The syntax above is ridiculous because 5.add(2) not valid: JavaScript expects a number (or "nothing") after 5. .. Since this is a global side effect (it will affect all numbers), unexpected interactions should be avoided.
Alternatively, <5> you can create a new Number object (5 is not a real instance of Number, although it uses Number.prototype!) And then copy the required methods. (I used to think this was the only way, but see KooiInc's answer - however, I'm not sure how correct it is to return a non-string from toString .)
function ops(a) { return { add: function(b) { var res = new Number(a + b)
However, remember that this introduces subtle issues:
typeof 5 // number typeof new Number(5) // object 5 instanceof Number // false new Number(5) instanceof Number // true
And so we need Number (SO search for "primitives" in JavaScript):
x = 5 x.foo = "bar" x.foo // undefined
Also, in combination with the cwolves answer, consider:
function number (n) { if (this === window) { // or perhaps !(this instanceof number) return new number(n) } else { this.value = n } }
Then both new number(2) and both number(2) will evaluate the new numbering object.
number(2).value // 2 new number(2).value // 2 number(2) instanceof number // true new number(2) instanceof number // true
Happy coding.
user166390
source share