Function scoping offers the only privacy in JavaScript.
So the canonical:
function Ctor(dep1, dep2) {
this._dep1 = dep1;
this._dep2 = dep2;
}
Ctor.prototype.foo = function() {
// use this._dep1/2...
}
...is problematic in that it offers no encapsulation for the injected dependencies.
An alternative (albeit slightly different in terms of location of foo
) that offers real encapsulation might be:
function factory(dep1, dep2) {
return {
foo: partial(foo, dep1, dep2), // or use bind (partial could be a library fn for partial application)
};
}
function foo(dep1, dep2) {
// use dep1/2
}
But I rarely see this pattern. Is there a good reason to not use the latter?