JavaScript Patterns–Benefits




- April 20, 2015

Rest of the Story:

Closures

  • By default, all variables and functions are added to the global scope, possibly causing naming conflicts
  • closures can be used to define scopes nested function have always accessed to all objects defined in the outer scope

if a nested function references an object defined in the outer scope, a closure is created and the object will not be destroyed when the outer function is returned

Prototype Pattern

  • similar to a class, a prototype is a blueprint for objects
  • encapsulates code into modules and takes it out of the global namespace
  • variables are assigned in the constructor
  • functions are defined in the prototype block
  • this keyword is required to reference variables and functions within one prototype
  • all functions are only loaded once into memory, no matter how many objects are created using the constructor
  • Allow functions to be overridden
  • variables are specific to one instance
  • functions are shared among all instances

Module Pattern

  • encapsulates code into modules and takes it out of the global namespace
  • allows definition of private/public members
  • if multiple objects are created, all functions are loaded into memory multiple times
  • less extensible than the prototype pattern
  • members in the return statement are public, members outside the return statement are private
  • does not require the use of a constructor and is often initialized using a self calling function (= singleton)

Revealing Module Pattern

  • Very similar to the module pattern
  • Cleaner separation between private members and public interface
  • Instead of public functions, an object literal is returned which contains references to the private functions which should be exposed

Revealing Prototype Pattern

  • very similar to the prototype pattern

  • adds the separation of private and public members from the revealing module pattern

  • if a method calls another method within the prototype, the 'this' is no longer the object but the calling method

  • 'this' can be passed as a parameter or

  • the method can be called with method name.call(this, anotherParam) which passes the context (the signature of "methodname" is just methodname(anotherParam)