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
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
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 () {…}
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
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
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
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
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?
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
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
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
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
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
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
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( )
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
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
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
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;
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
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