Javascript – What common programming problems are best solved by using prototypes and closures

closuresjavascriptlanguage-features

As much as I understand both concepts, I can't see how can I take advantage of JavaScript's closures and prototypes aside from using them for creating instantiable and/or encapsulated class-like blocks (which seems more of a workaround than an asset to me)

Other JS features such as functions-as-values or logical evaluation of non-booleans are much easier to fall in love with…

What common programming problems are best solved by using propotypal inheritance and closures?

Best Answer

  1. Closures are what makes functions as values useful. When you are passing the function, you almost certainly need it to take some context along. Which is exactly what closures do.

  2. Prototypes are just a simpler version of class inheritance. Instead of having instances and classes (represented by special kind of instances in dynamic languages anyway), you have just instances and the prototype is the class (and it's prototype is the base class). So they basically solve the same problems, just the prototypes are easier to implement (that's why JavaScript chose them), somewhat harder to use (well, just lack of syntactic sugar) and for better or worse easier to abuse.