r/programming • • Dec 19 '15

4 JavaScript Design Patterns You Should Know

https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
0 Upvotes

4 comments sorted by

4

u/inmatarian Dec 20 '15

Javascript

and

Race conditions occur in multi-threaded applications when more than one thread tries to access the same resource. Singletons are susceptible to race conditions, such that if no instance were initialized first, two threads could then create two objects instead of returning and instance. This defeats the purpose of a singleton. Therefore, developers must be privy to synchronization when implementing singletons in multithreaded applications.

excuse me?

1

u/Patman128 Dec 20 '15

Yeah, that is... what? Multithreaded? In JavaScript?

We have Web Workers but they run completely isolated, so there's no issues.

3

u/pointy Dec 20 '15

Those are idioms, not design patterns. Read this.

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.