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

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d… twitter.com/i/web/status/9…
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything huffingtonpost.com/entry/trump-te…
Retweeted by @dyardy Boston https://t.co/QmtMIF8P0F