JavaScript Patterns–Benefits


  • 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 access 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
  • allows 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 of the return statement are private
  • does not require the use of an 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 as a parameter or
    • the method can be called with, anotherParam) which passes the context (the signature of "methodname" is just methodname(anotherParam)



comments powered by Disqus


Recent Tweets

Maybe resolved itself, after resetting emulator and couple restarts - will let you know
@MillerMark A few weeks ago you tweeted that something huge/incredible was coming....what is/was it? (I am hoping s……
Oddly, it won't hit breakpoints in XF .net standard 2 project now either
@JamesMontemagno Updated to 15.7 preview 2 Visual Studio - now having lots of odd thread issues when starting debug……