SlideShare a Scribd company logo
1 of 103
JavaScript Pattern
allanhuang@eSobi.com
Agenda
 About

JavaScript
 Essential Practices
 Literals and Constructors
 Functions
 Object Creation Patterns
 Code Reuse Patterns
About Patterns
 What’s




Not for copy-and-paste
Useful abstraction
Template or model for solving

 Coding



Patterns?

Patterns

Design Patterns
vs. Antipatterns
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
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
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
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)
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
Essential Practices
Essential Practices
 Maintainable






code

Readable
Consistent
Predictable
Looks as be written by Same Person
Documented
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
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
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 !==
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”)
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 () {…}
Naming Convention
 Camel





case

constructors
functions
methods
variables: all lowercase words with underscore

 Constants:

use all capital letters
 Global variables: use all capital letters
Naming Convention
 Private


Underscore prefix(?)





scope

e.g. _getName()

properties
methods
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
Literals and Constructors
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()
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
Array Literal
 var

array = [ ];
 Array.isArray method



Added from ES5
Array toString()




[object Array]

Object toString()


[object Object]
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
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
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
Error Objects
 Error(),
Error()


SyntaxError(), TypeError()
SyntaxError()

name, message

 Throw…Catch
 Custom

error object
Constructor Syntax
Functions
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
Function
 Named



Function Expression

var add = function add() {…};
Incompatible with IE

 Unnamed




Function Expression

var add = function () {…};
Function Expression
Anonymous Function
Function
 Function



Declaration

function add() {…}
Inside other functions or the global scope

 Function’s


name

Pros



Debugging
Recursive call
API Patterns
 Help

you provide better and cleaner interface
to your functions





Callback Pattern
Configuration Objects
Returning Functions
Currying
Initialization Patterns
 Help

you perform initialization and setup
tasks without polluting the global namespace




Immediate Function
Immediate Object Initialization
Init-Time Branching
Performance Patterns
 Help



speed up the code

Memoization
Self-Defining Functions
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
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
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
Function Patterns
 Immediate


Return values







Function

var result = (function () {return…}());
var result = (function () {return…})();
var result = function () {return…}();

Bookmarklet
Self-contained modules
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
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?
Object Creation Patterns
Object Creation Patterns
 Namespace




pattern

A generic namespace function
All capital letters
Drawbacks




A bit more to type
Only global instance
Long resolution lookup
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
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)
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
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
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
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
Static Members
 No

instance-specific
 Public Static member



Be accessible outside
via Constructor

 Private



Static member

Not accessible outside
Using Closure feature
Object Constants
 All



capital letters

Math.PI
Number.MAX_VALUE

 General-Purpose




set(name, value)
isDefined(name)
get(name)

Constants object
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
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
Code Reuse Patterns
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
The Default Pattern (#1)


Child.prototype = new Parent( );
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
Rent-a-Constructor (#2)


function Child (…) {
Parent.apply(this, arguments);
}
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
Rent and Set Prototype (#3)


function Child (…) {
Parent.apply(this, arguments);
}
Child.prototype = new Parent( );
Rent and Set Prototype (#3)
 Benefits


Combine #1 and #2 patterns

 Drawbacks



Parent constructor is called twice
Parent members get inherited twice
Share the Prototype (#4)


Child.prototype = Parent.protoype;
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
A Temporary Constructor (#5)


var F = function( ) { };
F.prototype = Parent.prototype;
Child.prototype = new F( );
Child.uber = Parent.prototype;
Child.prototype.constructor = Child;
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
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
Prototypal Inheritance


function object (o) {
function F( ) { }
F.prototype = o;
return new F( );
}
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);
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
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
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( )
Design Patterns
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
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(?)
Iterator
 Purpose


Providing an API to loop over and navigate
around a complex custom data structure

 Additional



rewind( )
current( )

convenience methods
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
Decorator Implementation
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
Facade
 Purpose


Providing a more convenient API by wrapping
common methods into a new one

 Handle



browser events

stopPropagation( )
preventDefault( )
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
Proxy As a Cache
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
Mediator in Keypress Game
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( )
DOM and Browser
Patterns
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
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
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);
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;
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;
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
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);
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
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
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);
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
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
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
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>
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
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
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
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
Conclusion
 Q&A

More Related Content

What's hot

What's hot (13)

pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Java
JavaJava
Java
 
Java beans
Java beansJava beans
Java beans
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core java
Core javaCore java
Core java
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 

Similar to Java Script Patterns

Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
C# Summer course - Lecture 1
C# Summer course - Lecture 1C# Summer course - Lecture 1
C# Summer course - Lecture 1mohamedsamyali
 
Step talk
Step talkStep talk
Step talkESUG
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsSaurabh Narula
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overviewbwullems
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaMartijn Blankestijn
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patternsJavascript coding-and-design-patterns
Javascript coding-and-design-patternsHernan Mammana
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaMatteo Baglini
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introductionPeter Gfader
 

Similar to Java Script Patterns (20)

Java scriptforjavadev part2a
Java scriptforjavadev part2aJava scriptforjavadev part2a
Java scriptforjavadev part2a
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Oop java
Oop javaOop java
Oop java
 
Java basics
Java basicsJava basics
Java basics
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
C# - Igor Ralić
 
C# Summer course - Lecture 1
C# Summer course - Lecture 1C# Summer course - Lecture 1
C# Summer course - Lecture 1
 
Step talk
Step talkStep talk
Step talk
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patternsJavascript coding-and-design-patterns
Javascript coding-and-design-patterns
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introduction
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 

More from Allan Huang

Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Java JSON Parser Comparison
Java JSON Parser ComparisonJava JSON Parser Comparison
Java JSON Parser ComparisonAllan Huang
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System DevelopmentAllan Huang
 
eSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureeSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureAllan Huang
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Tomcat New Evolution
Tomcat New EvolutionTomcat New Evolution
Tomcat New EvolutionAllan Huang
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New EvolutionAllan Huang
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web DesignAllan Huang
 
Boilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementBoilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementAllan Huang
 
Build Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGapBuild Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGapAllan Huang
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 MultithreadingAllan Huang
 
HTML5 Offline Web Application
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web ApplicationAllan Huang
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data StorageAllan Huang
 
Weighted feed recommand
Weighted feed recommandWeighted feed recommand
Weighted feed recommandAllan Huang
 
eSobi Site Initiation
eSobi Site InitiationeSobi Site Initiation
eSobi Site InitiationAllan Huang
 
Architecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EEArchitecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EEAllan Huang
 

More from Allan Huang (20)

Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Drools
DroolsDrools
Drools
 
Java JSON Parser Comparison
Java JSON Parser ComparisonJava JSON Parser Comparison
Java JSON Parser Comparison
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
 
eSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureeSobi Website Multilayered Architecture
eSobi Website Multilayered Architecture
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Tomcat New Evolution
Tomcat New EvolutionTomcat New Evolution
Tomcat New Evolution
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New Evolution
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
 
Boilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementBoilerpipe Integration And Improvement
Boilerpipe Integration And Improvement
 
YQL Case Study
YQL Case StudyYQL Case Study
YQL Case Study
 
Build Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGapBuild Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGap
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
 
HTML5 Offline Web Application
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web Application
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data Storage
 
Weighted feed recommand
Weighted feed recommandWeighted feed recommand
Weighted feed recommand
 
Web Crawler
Web CrawlerWeb Crawler
Web Crawler
 
eSobi Site Initiation
eSobi Site InitiationeSobi Site Initiation
eSobi Site Initiation
 
Architecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EEArchitecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EE
 

Recently uploaded

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 

Recently uploaded (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

Java Script Patterns

  • 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
  • 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
  • 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
  • 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?
  • 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
  • 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( )
  • 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
  • 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
  • 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( )
  • 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