4 ms·
My only issue with doing the full-on module pattern is that, coming from a Python/Ruby background, I've stopped caring about the notion of private vs protected
by Pewpewarrows 15y ago
My only issue with doing the full-on module pattern is that, coming from a Python/Ruby background, I've stopped caring about the notion of private vs protected vs public, especially when considering testing. In other languages (like Java) I can add a dash of reflection magic in my unit-tests to get to hidden components, but that seems to be impossible using Javascript's module pattern. Take this snippet for example:
var Module = (function() {
var baz;
function foo(x) {
baz = x;
}
return {
bar: function() {
foo(42);
}
};
})();
There are several variations of the pattern, but that's the basic gist of it. Once it becomes non-trivial, how do I test foo? How do I verify baz's state? Furthermore, if I wanted to extend this with one of Javascript's sub-class implementations, how would my new slightly-different "bar" be able to use "foo"?
Besides my general opinion of private variables and methods being unnecessary, unless someone has a good fix for those two problems, I'll never consider using the module pattern in any code that I write.
- tbranyen 15y agoThis pattern uses an immediately invoked function expression (IIFE) to scope dependencies and shorten variable names. Be smart about your code, you can expose anything you want and attach anything to the module object for testing.