I have two classes, one depends on another. It is implemented like this:
class myns.ClassA
constructor(@serviceB): ->
publicFunctionA: ->
privateFunctionB.call this
privateFunctionB = ->
@serviceB.someFunction()
then I instantiate it in a glue piece:
myns.classA = new myns.ClassA(myns.serviceB)
and use as:
myns.classA.publicFunctionA()
The problem here is I want to access serviceB from privateFunctionB. Is there more appriopriate way of doing this besides using call ?
Or perhaps my entire approach is tainted too much by my Java backgound? What I need are interdependent code modules, some kind of equivalent to singleton services. I know I could use coffeescript class functions and avoid instantation but how to handle injecting serviceB in a clean way then?
Regarding your question about Java idioms:
There is no notion of public and private in CoffeeScript. Your
privateFunctionBis just a normal function declared in the closure of the class. It is in general not a great practice to simulate private functions, because such functions have very different semantics (for example ifprivateFunctionBwas a variable outside your class it would get overwritten, whereas no such risk exists forpublicFunctionA).Therefore the best is to write both functions as normal class properties (that is what you call public functions. Then your code simplifies to this:
Another thing you could do for singleton-like things that you can do in CS but not in java is to use global variables. This is often not considered best practice, but it depends on your application (e.g. it’s a big no no if writing library code, but might be ok in an end-user sort of thing, depending on usage).
Furthermore you could also consider avoiding the whole class thing and just writing it as a plain object, this possibly will be a good idea if there will be no instances and you plan on doing no subclasing etc.