By returning the this keyword I can chain the 2 methods instead of calling them one by one.
I believe it happens because it has to do with Closure where it kind of holds the current value in a state memory, but I need some help in order to really understand what’s happening here. Thanks in advance for any tips…
The calc object is an instance of a new Calculator. When calc is used, the this keyword refers to that calc object.
Where the this keyword is returned, that results in a reference to the calc object being returned. From that returned calc object you can then access any of its methods, including add and print.
For example, you can chain the add methods together too.
Actually, calc.print() doesn’t take any arguments, so passing the result of calc.add() (which is undefined anyway) doesn’t do anything; it just works because calc.add() updates the state of calc, so this is what actually happens:
calc.add(10)
calc.print()
Returning this simply makes for a fluent API, but doesn’t affect the logic as such (e.g. whether a method call updates the object in place, or returns a clone with updated state, or the immediate result of a certain operation).