The example you gave produces a constructor that wraps a handful of
instance method definitions along with several function declarations -
which I'm arguing could just as easily be outside of that function
declaration, but inside of an IIFE.
There are two issues here:
1) “Private methods” could be moved outside to the module level (IIFE
level if you wish).
This is true, but would necessitate passing the private state into these
methods: `callListener` would need `options`, which then propagates to an
extra parameter on `callListenersForSync` and `callListenersForAsync`.
Obviously this problem multiplies as you add more private state to the
object, eventually ending up passing around a “secrets” object containing
all your private state, which is a bundle of joy to program against.
</sarcasm>
2) “Public methods” cannot be moved outside to the prototype level.
If instead of `that.publish = function () { ... }` inside the constructor,
I had `Publisher.prototype.publish = function () { ... }` outside the
constructor, then the function body could not access the “private instance
variables” `normalListeners` and `oneTimeListeners`, or the constructor
parameter `options`.
The only way to allow a `Publisher.prototype.publish` method to access
this per-instance state would be to un-encapsulate it, making it public so
that they could be accessed as e.g. `this._normalListeners`.
This is what I mean when I say I eschew the prototypal pattern in favor of
the closure pattern. All of my methods are instance methods, because they
need access to private, encapsulated state.
Hope I'm not misunderstanding the issue, but have you considered
using modules/namespacing to get modularity+privacy?
You could have a module with internals, imported into those modules
that define subclasses with access to the private internals. If you are
using closures to approximate modules, you could pass the internals
to the closure defining the subclass instead of passing internals to
every method.
Claus
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss