r/programming • u/javascriptmyface • Dec 19 '15
4 JavaScript Design Patterns You Should Know
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
0
Upvotes
3
1
u/Y_Less Dec 20 '15
Something I'm not sure a lot of people know - constructors can explicitly return objects, so doing:
var x = new Obj();
Obj = function () { return x; }
var y = new Obj();Is equivalent to doing:
var x = new Obj();
var y = x;Despite the fact that "new" was used twice. The point being that if you really must write singletons you can use this method to wrap the constructors in a function that always returns the same object even when requesting a new one. Then, if at some later date you decide that you no longer want everything to be singletons you can remove the wrapper and leave the remainder of your code that is already using "new" alone.
4
u/inmatarian Dec 20 '15
and
excuse me?