Java Script Patterns

  • 233 views
Uploaded on

Refer to an IT book "O'Relly JavaScript Patterns".

Refer to an IT book "O'Relly JavaScript Patterns".

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
233
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
8
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. JavaScript Pattern allanhuang@eSobi.com
  • 2. Agenda  About JavaScript  Essential Practices  Literals and Constructors  Functions  Object Creation Patterns  Code Reuse Patterns
  • 3. About Patterns  What’s    Not for copy-and-paste Useful abstraction Template or model for solving  Coding   Patterns? Patterns Design Patterns vs. Antipatterns
  • 4. About JavaScript  Script   language Interpreted language vs. Compiled language  Object-oriented  Primitive types   Native objects   number, string, boolean, null, undefined Number, String, Boolean, Date, Array, Function… User-defined
  • 5. About JavaScript  Prototype-based  No Classes   vs. Class-based language Prototype   language Alteration prototypes during run-time Dynamic typing  Values have types but variables do not
  • 6. About JavaScript  First-class   functions Function literals or Function types Functions as first-class objects  Own properties and methods  ECMAScript    5 (be called ES5, for short) Vs. ECMAScript 3 (ES3) Strict mode Library extensions
  • 7. Tools for JavaScript  Firebug   If (console && console.firebug) Object inspection   Timing and profiling   console.time(message) Stack traces   console.dir(object) console.trace() Nested grouping  console.group(message)
  • 8. Tools for JavaScript  Code  JSLint  Strict mode-compliant  Web   Quality Tool Page Performance Diagnostics Tool YSlow from Yahoo! Page Speed from Google  Books   about web pages tuning High Performance Web Sites, O’Reilly Even Faster Web Site, O’Reilly
  • 9. Essential Practices
  • 10. Essential Practices  Maintainable      code Readable Consistent Predictable Looks as be written by Same Person Documented
  • 11. Essential Practices  Global  Minimize Globals    variables Always use var to declare variables Single var Pattern Other ways…   Namespacing pattern Self-executing immediate function  Can Global Variables be delete?  Hoisting problem
  • 12. Essential Practices  For  Loop Iterate over arrays or array-like objects     Cache the length of the array ++ and -- vs. i += 1 and i -= 1 Use one less variable Count down to 0  For-in  Loop Iterate over non-array objects  hasOwnProperty() method
  • 13. Essential Practices  Augmenting   Built-in Prototypes Unpredictable code Except…   Future ECMAScript version or JavaScript implementation Custom property or method does not exist  Switch Pattern  Avoiding Implied Typecasting  == and != vs. === and !==
  • 14. Essential Practices  Avoiding     setInterval(), setTimeout() and new Function() eval() Interfere with the scope chain Function() is like a sandox JSON.parse() method  Use    eval() parseInt() parseInt(string, radix) +”08” Number(“08”)
  • 15. Code Convention  Curly Braces {…}    Always use {…} if only one statement in an if or a for Opening Brace Location White space        for (var i = 0; i < 10; i += 1) {…} for (var i = 0, max = 10; i < max; i += 1) {…} var a = [1, 2, 3] var o = {a: 1, b: 2} myFunc(a, b, c) function myFunc( ) {…} var myFunc = function () {…}
  • 16. Naming Convention  Camel     case constructors functions methods variables: all lowercase words with underscore  Constants: use all capital letters  Global variables: use all capital letters
  • 17. Naming Convention  Private  Underscore prefix(?)    scope e.g. _getName() properties methods
  • 18. The Next…?  Write   Comments Write to Be Read Write API Docs  Peer Reviews  Tools for code better   Run JSLint Minification   Yahoo! YUI Compressor Google’s Closure Compiler
  • 19. Literals and Constructors
  • 20. Object Literals  var   object = { }; Change the values of properties and methods Delete / Add properties and methods  Blank  object / Empty object inherited from Object.prototype  Object  constructor Scope resolution  Look up the scope chain from the place you calling new Object()
  • 21. Constructor  Add reusable methods to the prototype, but not the constructor function  Return this or any other object  Invoke the constructor without new  Return another object: that  Prototype is not available  Self-Invoking constructor
  • 22. Array Literal  var array = [ ];  Array.isArray method   Added from ES5 Array toString()   [object Array] Object toString()  [object Object]
  • 23. JSON  Syntax     Similar to Object Literal Property names are wrapped in “…” No Functions Literal No Regular Expression Literal  JSON.parse()    / JSON.stringify() Browser build-in native methods jQuery.JSON YUI.JSON
  • 24. Regular Expression Literal  var re = /pattern/gmi;  var re = new RegExp(‘pattern’, ‘gmi’)     Global matching: g Multiline: m Case-insensitive matching: I Same regular expressions if their expressions are equal each other
  • 25. Primitive Wrappers  Built-in    constructor Number() String() Boolean()  Useful methods work on primitives that is temporarily converted to an object  Primitives cannot be augmented with properties or methods
  • 26. Error Objects  Error(), Error()  SyntaxError(), TypeError() SyntaxError() name, message  Throw…Catch  Custom error object
  • 27. Constructor Syntax
  • 28. Functions
  • 29. Function 2 very important features  They are Objects They provide Local Scope   Can     be… Created dynamically, Assigned to variables Augmented, Deleted in a few special cases Passed as arguments, Returned by other functions Their own properties and methods
  • 30. Function  Named   Function Expression var add = function add() {…}; Incompatible with IE  Unnamed    Function Expression var add = function () {…}; Function Expression Anonymous Function
  • 31. Function  Function   Declaration function add() {…} Inside other functions or the global scope  Function’s  name Pros   Debugging Recursive call
  • 32. API Patterns  Help you provide better and cleaner interface to your functions     Callback Pattern Configuration Objects Returning Functions Currying
  • 33. Initialization Patterns  Help you perform initialization and setup tasks without polluting the global namespace    Immediate Function Immediate Object Initialization Init-Time Branching
  • 34. Performance Patterns  Help   speed up the code Memoization Self-Defining Functions
  • 35. Callback Patterns  Callback  Function Template Method  Scope   Pass the object that callback belonged to Pass the method (callback) as string  Asynchronous  Cons  Out of order  Timeout   setTimeout() setInterval() Event Listeners
  • 36. Function Patterns  Returning   Function Return another function Use Closure to store private data  Self-Defining     Function Create a new function assign to the same variable Initial work to be done only once Lazy function definition Original function will be lost when it redefined
  • 37. Function Patterns  Immediate   Self-Invoking, Self-Executing Execute a function as soon as it is defined     Function (function () {…}()); (function () {…})(); A scope sandbox for initialization code Pass arguments to immediate functions
  • 38. Function Patterns  Immediate  Return values      Function var result = (function () {return…}()); var result = (function () {return…})(); var result = function () {return…}(); Bookmarklet Self-contained modules
  • 39. Function Patterns  Immediate  init() after object is created    ({…}).init(); ({…}.init()); Drawback   Minification No return values  Init-Time   Object Initialization Branching Load-time branching e.g. Browser sniffing
  • 40. Function Patterns  Memoization  Pattern Use Properties to store Cached data  arguments.callee  Configuration  Objects Substitute for a set of passed arguments  Curry Partial Application  Currying   When to Use Currying?
  • 41. Object Creation Patterns
  • 42. Object Creation Patterns  Namespace    pattern A generic namespace function All capital letters Drawbacks    A bit more to type Only global instance Long resolution lookup
  • 43. Object Creation Patterns  Declaring  Dependencies Declare the modules your code relies on at the top of your function or module    Realize the specific JS files are needed Easy to find and resolve dependencies Perform global symbol resolution only once
  • 44. Private, Protected, or Public  Private  Members Using Closure to access private members  Function Declaration as private functions  Privileged   Methods Public methods have access to the private members (properties or methods) A returned private variable can be modified if it’s an object or array (Passed by Reference)
  • 45. Private, Protected, or Public  Private members always are created when the constructor is invoked  Add public reusable members to the prototype property of the constructor  Revelation  pattern Reveal private functions as public methods
  • 46. Module Patterns  Provide structure and help organize your code as it grows  In common use all over our web applications  Combine the following patterns     Namespaces Immediate Functions Private and Privileged members Declaring dependences
  • 47. Module Patterns  Reveal  Module Pattern Return the object has triggers of private functions  Modules  that Create Constructors Return the constructor function  Importing Globals into a Module
  • 48. Sandbox Pattern  Drawbacks   A of Module pattern No way to have 2 versions of the same application or library Long, dotted names to type and resolve at runtime Global Constructor  Adding Modules
  • 49. Static Members  No instance-specific  Public Static member   Be accessible outside via Constructor  Private   Static member Not accessible outside Using Closure feature
  • 50. Object Constants  All   capital letters Math.PI Number.MAX_VALUE  General-Purpose    set(name, value) isDefined(name) get(name) Constants object
  • 51. Chaining Pattern  Call methods on an object after the other  Pros   Save some typing Create more concise code  Cons  Debug code more difficult  Always return this if your method has no return value
  • 52. method() Method  Help you define the whole “class” with a single statement  Drawback   Debug code more difficult Add methods to this is inefficient   Methods are re-created with every instance Consume more memory  Reusable methods should be added to the prototype property of the constructor
  • 53. Code Reuse Patterns
  • 54. To Reuse Code…  Inheritance  That is one way for us to reuse code, but not the only way  Composition  Prefer object composition to class inheritance  Prototype   / Delegation Inheritance Prototype Constructor
  • 55. The Default Pattern (#1)  Child.prototype = new Parent( );
  • 56. The Default Pattern (#1)  Benefits  Inherit parent properties and parent prototype members  Drawbacks   Inherit parent properties added to this and the child prototype properties Can’t pass parameters to the child constructor  General  rule of thumb with constructors Reusable members should be added to the prototype
  • 57. Rent-a-Constructor (#2)  function Child (…) { Parent.apply(this, arguments); }
  • 58. Rent-a-Constructor (#2)  Benefits   Borrowing Constructor Pattern Only inherit parent properties added to this inside the parent constructor  Drawbacks  Can’t inherit parent prototype members  Multiple Inheritance by Borrowing Constructors
  • 59. Rent and Set Prototype (#3)  function Child (…) { Parent.apply(this, arguments); } Child.prototype = new Parent( );
  • 60. Rent and Set Prototype (#3)  Benefits  Combine #1 and #2 patterns  Drawbacks   Parent constructor is called twice Parent members get inherited twice
  • 61. Share the Prototype (#4)  Child.prototype = Parent.protoype;
  • 62. Share the Prototype (#4)  Benefits   Child prototype is equals to parent prototype All objects share the same prototype  Drawbacks  One child modified the prototype that affects all parents
  • 63. A Temporary Constructor (#5)  var F = function( ) { }; F.prototype = Parent.prototype; Child.prototype = new F( ); Child.uber = Parent.prototype; Child.prototype.constructor = Child;
  • 64. A Temporary Constructor (#5)  Benefits   A proxy function between child and parent Parent constructor members adds to this are not inherited  Holy    Grail version Storing super (uber) class uber Resetting constructor pointer Use an immediate function to store proxy function in it’s closure
  • 65. Klass  Emulating  Class A generic klass function  Implementation    Create a Child( ) constructor function Inherit parent via Holy Grail pattern Add parent members to child prototype
  • 66. Prototypal Inheritance  function object (o) { function F( ) { } F.prototype = o; return new F( ); }
  • 67. Prototypal Inheritance  Feature Modern Classless Pattern  A generic object function  Create a child object gets its functionality from parent object Addition to ES5    var child = Object.create(parent);
  • 68. Inherit by Copying Properties  Feature   A  A generic extend function Create a child object gets its functionality from parent object by copying deep copy version extendDeep
  • 69. Mix-ins  Feature   A generic mix function Create a child object gets its functionality from any number of parent objects by copying  Multiple Inheritance Implementation
  • 70. Borrowing Methods  Feature   A   A generic bind function Use some methods without inheriting other methods common use for this pattern Array.slice.call(arguments) Array( ).slice.call(argument)  Addition  to ES5 Function.prototype.bind( )
  • 71. Design Patterns
  • 72. Singleton  Purpose  Creating only one object of a “class”  New instance via Object Literal  New instance via Constructor    Store in a Global Variable Cache in a Static Property of the constructor Wrap in a Closure   Private Static Member pattern Self-Defining Functions
  • 73. Factory  Purpose  A method that creates objects of type specified as a string at runtime  Map object types to the constructors that create different objects  Built-in Object Factory  new Object(?)
  • 74. Iterator  Purpose  Providing an API to loop over and navigate around a complex custom data structure  Additional   rewind( ) current( ) convenience methods
  • 75. Decorator  Purpose  Tweaking objects at runtime by adding functionality from predefined decorator objects  Undercorating   / Undoing a decoration Implementation Using a Array It’s no need to use Inheritance
  • 76. Decorator Implementation
  • 77. Strategy  Purpose  Keeping the same interface while selecting the best strategy to handle the specific task (context)  The validator is generic and could be kept like this for all validation use cases
  • 78. Facade  Purpose  Providing a more convenient API by wrapping common methods into a new one  Handle   browser events stopPropagation( ) preventDefault( )
  • 79. Proxy  Purpose  Wrapping an object to control the access to it, with the goal of avoiding expensive operations  Proxy serves as a guardian of the “real subject” and tries to have the real subject do as little work as possible  Proxy As a Cache   More less Network Round-trips Memorization Pattern
  • 80. Proxy As a Cache
  • 81. Mediator  Purpose  Promoting loose coupling and then helping improve maintainability  Independent colleagues don’t communicate directly, but through a mediator who notifies the change to any other colleagues
  • 82. Mediator in Keypress Game
  • 83. Observer  Purpose   Loose coupling by creating “observable” objects that notify all their observers when an interesting event occurs Subscriber (Observer) / Publisher (Subject)  Publisher    has important methods subscribe( ) unsubscribe( ) publish( )
  • 84. DOM and Browser Patterns
  • 85. Separation of Concerns 3     In     main concerns in web application Content - HTML Presentation - CSS Behavior - JavaScript Practice… Page is still readable if CSS is off Page perform main purpose if JavaScript is off Not using inline event handlers or style attributes Using meaningful HTML elements
  • 86. DOM Access  Bottleneck  DOM is separated from JavaScript engine  Good    Avoiding DOM access in loop Assigning DOM reference to local variables Using selectors API     Parts… document.querySelector(“#widget”); document.querySelectorAll(“.widget”); Cache the length of HTML collections document.getElementById(“id”) is fastest way
  • 87. DOM Manipulation  Bottleneck  Modify DOM to repaint the browser’s screen and recalculate element’s geometry  Batch the changes and performing them outside of the live document tree  Use a document fragment to contain new nodes   var frag = document.createDocumentFragment(); Make all change to the Clone of root of subtree   var newnode = oldnode.cloneNode(true); oldnode.parentNode.replaceChild(newnode, oldnode);
  • 88. Events  Bottleneck  Event handling in IE (version < 9) and W3Cconforming implementations is different  Access   event Passed to Callback event handler Use onclick property through window.event  e = e || window.event;  Access  target of event src = e.target || e.srcElement;
  • 89. Event Handling  W3C-conforming   Event Capturing Cancel Event Propagation     e.stopPropagation(); Prevent default action   IE e.preventDefault(); (version < 9) Event Bubbling Cancel Event Propagation   cancelBubble = true; Prevent default action  returnValue = false;
  • 90. Event Delegation Pattern  Benefits  Suitable for Event Bubbling  Reduce the number of event listeners attached to separate nodes Better performance and cleaner codes   Drawbacks  Filter out the uninteresting events  Use 3rd JavaScript library
  • 91. Event Handling 3rd-party API  jQuery  version 1.0 ~ 1.3      $(target).bind(event, callback); $(target).trigger(event); $(target).one(event, callback); $(target).live(event, callback); version 1.4.2 ~  $(container).delegate(target, event, callback);  Yahoo!  YUI Y.delegate(event, callback, container, target);
  • 92. Long-Running Scripts  Issue  Browser complains a Long-Running Script and ask user if it should be stopped  Solutions  setTimeout()   Use 1ms timeout chunks cause task to complete slowly overall, but browser UI will remain responsive WebWorkers  Web workers provide background thread support in the browser
  • 93. Remote Script  AJAX   (Asynchronous JavaScript and XML) XMLHttpRequest Restricted same-domain  JSONP  HTML Script element Injection    (JSON with Padding) script.src = url; Execute a client-side callback with server-side JSON data passed from different domain Unrestricted cross-domain
  • 94. Remote Script  Frame  HTML iFrame element Injection  iframe.src = url;  Image  Beacons pattern Send data to server but not expecting a response   new Image().src = “http://...”; Response with 1x1 GIF image or “204 No Content” Content  HTML5  Cross-document messaging  otherWindow.postMessage(string, targetOrigin);
  • 95. Deploying JavaScript  Combining  Benefits   Scripts Speed up Page Loading Drawbacks  More preparations before deploying into production   Lose some of the caching benefits   Help from Ant tool Spilt up to 2 bundles: barely change and hardly change Come up with some naming and versioning pattern for bundle
  • 96. Deploying JavaScript  Minifying   Yahoo! YUI Compressor Google’s Closure Compiler  Compressing  Enable GZIP compression in server-side  Expires   Header Stay files in browser cache as far as possible Rename files if they have been changed  Construct  or Using CDN Google, Microsoft, Yahoo! hosts popular libraries
  • 97. Using Popular CDN  Benefits  Decreased Latency   Increased Parallelism   Clients will automatically target the closest available server in the network Eliminate one request to your site, allowing more of your local connect to download in parallel Better Caching  Clients will only need download it once if it had been visited on another website using the same CDN
  • 98. Loading Strategies  Minimize  blocking effect Place <script> at the closing </body> element  HTTP Chunking  Non-blocking downloads *.js    Load script with an AJAX and eval() it as a string Using defer / async attributes of <script> Using Dynamic <script> Pattern   Append this dynamic <script> to <head> or <body> Also insert this dynamic <script> before the first available <script>
  • 99. Dynamic <script> Pattern  Drawbacks  Any other <script> can’t rely on the main *.js being load on the page  Solution   Using anonymous function to wrap separate inline scripts into a function and add each function into an empty array Loop through this array in main script and execute all of them
  • 100. Better Dynamic <script> Pattern  Lazy  Loading Load external *.js unconditionally after page load event  Loading   on Demand Load only the parts *.js that are really needed Create a method that loads <script> dynamically and execute a callback when <script> is loaded   In W3C-conforming, subscribe load event In IE (version < 9), subscribe readystatechange event and look for a readystate === “load” or “complete” load complete
  • 101. Better Dynamic <script> Pattern  Preloading    JavaScript Load external *.js are not needed on current page but on following pages without parsing and executing *.js immediately This works not only for *.js, but also *.css and images, e.g. *.jpg, *.png etc. Drawbacks   The presence of user agent sniffing Some browsers probably have a separate cache for images, so preloading *.js or *.css will not be used
  • 102. Better Dynamic <script> Pattern  Preloading  JavaScript Create a method using init-time branching pattern to handle browser sniffing   Using invisible <object> in W3C-conforming Using new Image().src in IE
  • 103. Conclusion  Q&A