class A
constructor: ->
method: ->
In the above example, method is not bound to the class and neither is constructor.
class B
constructor: ->
method: =>
In this case, method is bound to the class. It behaves as you expect a normal object method to behave and has access to all of class B’s fields. But the constructor is not bound? That seems strange. So i tried the following.
class C
constructor: =>
method: =>
This doesn’t compile. I would expect the syntax to be the same on all methods that are bound to a class.
I would like to regard the -> operator as a static operator and the => operator as a dynamic operator. But it doesn’t seem like you can. If you could, a method with the -> operator could not be called with super. But, in actuality, you can. Why does this make sense for the syntax of an object oriented language? This seems to not agree with most object oriented languages inheritance rules.
Try looking at how the code compiles. When you use
=>, the methods are bound inside the constructor. Thus, it doesn’t make any sense to use=>for a constructor – when would it be bound?I’m not sure about your issue with
staticvs.dynamicoperators, but you can definitely call methods defined with the->operator withsuper. The only thing->vs=>affects is that the=>ensures thatthisis the object in question regardless of how it is called.Summary of comments:
Calling the difference between
->and=>analogous to static vs. dynamic (or virtual) does not quite convey what those operators do. They are used to get different behavior from javascript’sthisvariable. For example, look at the following code:The difference is in the second way we call each method: if the method is not “bound” to the object, its
thisis set by looking at what precedes the method call (separated by a.). In the first case, this isc, but in the secondfisn’t being called on an object, sothisis set towindow.method2doesn’t have this problem because it is bound to the object.Normally, you can think of the the constructor function automatically being bound to the object that it is constructing (thus, you can’t bind it with
=>). However, its worth noting that this isn’t quite what’s happening, because if a constructor returns an object, that will be the return value of the construction, rather than thethisduring the constructor.