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

Retweeted by @dyardy Hey C# peeps, we’re trying C# in browser with reference content. Try it here: docs.microsoft.com/dotnet/csharp/… reply with feedback /cc @LadyNaggaga
23 Amazing Vintage Photographs Taken Inside WWII Tank Factories ~ vintage everyday vintag.es/2017/10/23-ama…
When is AI NOT Search? Artificiality intelligence==Search Engine (there cases when this is not true)
@projectedxyz Large data vs big data? Industry has so misused buzz words to sell products, and so you end up nothi… twitter.com/i/web/status/9…