r/javascript • u/javascriptmyface • Dec 19 '15
4 JavaScript Design Patterns You Should Know
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know4
u/Gilgw Dec 19 '15
I don't see any difference between the module pattern and the revealing module pattern examples. The privacy of local variables is maintained in both cases, it seems?
3
Dec 19 '15
In the examples given, there is no difference. However in the revealing module pattern you can pick and choose which items you eventually "reveal" in the returned object. The items you choose not to reveal are then "private" as it were.
4
Dec 19 '15
TeslaModelS.prototype = function() {
go: function() {
// Rotate wheels
},
stop: function() {
// Apply brake pads
}
return {
pressBrakePedal: stop,
pressGasPedal: go
}
}();Surely that definition of the go and stop functions does not work like this, because it is using the go: function syntax where it should use the var go = function syntax.
EDIT:
Also
return : {
// declare public variables and/or functions
}return : {? Surely that is invalid syntax?
2
u/strident-octo-spork Dec 19 '15
I'd add one more to this list ... in fact I would make it the most important. I'll preface this with the disclaimer that module patterns can be important if you are writing code to be used by 3rd parties, but there is no need to do it for internal code. note what methods/variables are public and having coding standards. use standard APIs for object creation. Use bundlers/minifiers to produce module code with private members. Most source to source compilers or bundlers like webpack, browserify, rollup, GCC can take your normal code and turn it into an AMD, CJS, IIFE, whatever format.
// _fields are private
class Example {
constructor(name, x, y) {
this.name = name;
this._x = x;
this._y = y;
}
doSomething(a, b) {
return a * x + b * y;
}
_secret() {
// some private method
}
}And to make it a singleton... just export a new'd version.
5
u/madole Dec 20 '15 edited Dec 21 '15
The Singleton is the single most painful pattern (or anti pattern) I've had the displeasure of working with.
Don't get me wrong, they have use cases, but they are rarely implemented correctly in Javascript and I'd say 99% of the time if you're finding yourself wanting to implement a singleton, you've taken a wrong architecture decision at some point that you might want to reevaluate.