JavaScript Patterns–Benefits

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 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 methodname.call(this, anotherParam) which passes the context (the signature of "methodname" is just methodname(anotherParam)

Author

Admin

comments powered by Disqus

Categories

Recent Tweets

"Setting up and Getting Started with Power BI Embedded | Data Exposed" channel9.msdn.com/Shows/Data-Exp… #webcast #feedly
Retweeted by @dyardy @scottgu @victoriabeckham Worlds collide, double take on that photo!
@scottgu @victoriabeckham Worlds collide, double take on that photo!
@projectedxyz It is really easy, what are you doing (isn't this data which on the web)