Of course you should implement that MyNumber thing with prototypes, too, because it is much more efficient.
–
BergiFeb 18 '12 at 4:19

The valueOf() is necessary?, I mean, must I always end my chainings with some kind of function that returns the val?
–
mithril333221Feb 18 '12 at 4:23

@mithril333221 - to make chaining work, the return value from each method MUST be an object of the right type. If you want something other than that out of the object, you have to call a method to get that info.
–
jfriend00Feb 18 '12 at 4:28

Yes and no. Of course you will need a result function, else you still have an Object. If thats OK, you don't need one, but it's the only way to get the native value back. Yet, valueOf() is somewhat special, just as toString(): It is used for the automagic type conversion. For example, new MyNumber(5)+1 === 6 :-)
–
BergiFeb 18 '12 at 4:34

I am personaly not a big fan of method chaining since it restricts you to a predefined set of functions and there is kind of an impedance mismatch between values inside the "chaining object" and free values outside.

I want to know what restrictions are
–
mithril333221Feb 18 '12 at 4:28

I meant that if you want to do a "chaining method' aproach you need to know what all the chainable methods will be when you define the chainer (since you need to add a method to the chainer prototype for each function). On the other hand, the function composition version doesn't need to know the functions beforehand so you can pass anything you want to it.
–
hugomgFeb 18 '12 at 4:32

Still, you can add functions to the prototype every time you need them; the problem is just that they have to fit into the chainer construct with return this and use this._value. The downside of composition is that a library would pollute the global namespace, and a namespace to pull them together makes composition syntax harder.
–
BergiFeb 18 '12 at 4:51

1

@Bergi: While it is true that dynamic monkey patching gives tons of lexibility, it is still a pain to mess with the chainer like that and it also does not play very well one-shot anonymous functions. (Anyway, its a matter of personal choice in the end. I personaly try to only create an OO interface if I think I really need the polymorphism and dynamic dispatching)
–
hugomgFeb 18 '12 at 5:01

Yes, certainly the choice is all about the type of values you're dealing with. +1 for that
–
BergiFeb 18 '12 at 5:05

In order to avoid having to call toValue at the end of the chain as in @Bergi's solution, you can use a function with attached methods. JS will call toValue automatically when trying to convert to it a primitive type.