Coffeescript Instance Method Encapsulation In An Object
Say I have a Coffeescript class: class Foo MyMethodsBar: () => 'bar' MyMethodsBaz: () => 'baz' Is there any way to encapsulate methods like this (not working): class Foo
Solution 1:
Nope, this is not possible, unless you create MyMethods
inside the constructor and bind this
to the methods. At which point you pretty much loose the benefits of using a class.
That's because when you call a method via f.MyMethods.bar()
, this
will refer to f.MyMethods
. To prevent that, you could bind bar
to specific object beforehand. However, at the moment you are defining bar
, the instance of Foo
to which this
should refer to (f
) does not exist yet, so you can't bind it outside of the constructor.
You could call the method with f.MyMethods.bar.call(f)
, but that's rather cumbersome.
Post a Comment for "Coffeescript Instance Method Encapsulation In An Object"