more detail and better format click here
- JavascriptPattern
- design pattern
- coding pattern
- Antipattern
- problems > sloves
- Object-Oriented
- No Classes
- Prototypes
- Enviroment(browser)
- provide host object
- console.log
- console.dir
- problem
- forget var
- access to global
- single var pattern
- hoisting
- DOM
- .length
- single var pattern
- ++ to += 1
- .hasOwnProperty()
- case + break
- endswith default
- false === 0
- '' === 0
- != and == only use to compare =null and = undefined
- avoid eval
- JSON.parse()
- setInterval()\setTimeout()\Function() constructor
- in Function constructor eval scope is global
- wrap eval in immediate function,avoid pollution
- parseInt("08 hello")
- Number("08")
- + "08"
- indentation
- function
- loops
- ifs
- switches
- object properties
- curly braces
- use it even only one statement of if or for
- open brace location
- same line
- white space
- white space
- after ';'
for (let i = 0; i < 10; i ++){...}
- initial multiple variables
for (let i = 0, max = myarray.length; i < max; i ++){...}
- after ',' in array
arr = [1, 2, 3]
- after object properties
let o = {a: 1, b: 2}
- function arguments
function(a, b, c)
- before and after '{'
function foo() {...}
- anonymous function
let foo = function () {}
- operators
+ - * / < > <= >= === !== && || +=
- blank line for seperate unite
- after ';'
- white space
- indentation
- upper camel constructor(able to new)
function MyConstructor(){...}
- lower camel function
function myFunction() {}
- lowercase and underscore variables
my_name
- Capital Name for constant or global variables
let PI = 3.14
- underscore first private member
_getScore(){...}
- upper camel constructor(able to new)
- SDK(software developer kit)
- YUIDoc(Yahoo!User Interface)
- /*/
- Object literal {} no new Object(Number,String)
- build-in(Array,Number,String)
- custome constructor
- invoke with new
- customer return value(without inheritant properties, and lose this prototype)
- pollute global(this-->global)
- Self-Invoke Constructor
- []
- new Array(.length) new Array(3) = ['undefined', 'undefined', 'undefined']
- parse json: JSON.parse()
- opp: JSON.stringify()
- i/g/m
- /rules/igm
- number, string, boolean, (null, undefined: without constructor)
- avoid new String Number Boolean
- properties cannot augment
- Error(
throw{name:..., message...}
- Disambiguation of Teminology
- named function
let foo = function foo() {}
- unnamed function
let foo = function () {}
- foo.name = ''
- function declaration
function foo() {}
- named function
- Declarations Versus Expressions: Names and Hoisting
- Function's name Property
- Function Hoisting
- delaration hoist both name('foo') and implementation
- Disambiguation of Teminology
- Callback Pattern
- function (callback)
- scope:
function (callback, obj) {callback.call(obj,found)}
- Asynchronous Event Listeners
- click, keypress, mouseover, mousemove
- Timeouts
- setTimeOut
- setInterval
- Callbacks in Libraries
- focus on core functionalities
- provide hooks
- Returning Functions
- Configuration Objects
- Cleaner API
- no need to remember the parameters and order
- skip the optional
let conf = {}; addPerson(conf)
- Curry
- Function Application
- apply/call
- Partial Application
- Currying
- schonfinkelize()
- when to use
- Call same function and pass mostly the same parameters
- Function Application
- Callback Pattern
- Immediate functions(IIFE Immediate-Invoke function execuate)
(function (args) {}(args))
- return value
- Benifits and Usage
- wrap without global variavles
- wrap individual features into modules
- Immediate object initialization
{init:function () {}}.init()
- one-off task, or return this
- Init-Time Branching
- test certain condition only once(browser sniffing)
- Immediate functions(IIFE Immediate-Invoke function execuate)
- Function Properties--Memorization
- If property already exist, no need redo again
- myFunc.cache = {}
myFunc.cache[param]
JSON.stringify(Array.prototype.slice.call(arguments))
- Self-Defining Functions
- overwrite
- singleton
- Function Properties--Memorization
- Namespace Pattern
- global cleaner
MYAPP.namespace('MYAPP.module1.module2')
- Declare dependency
- upfront the function dependencies or modules
- less code when minify
- Private priorities and methods
- public
{myprop: 1}
getMyprop: function () {return this.myprop}
function Gadget() {this.name = 'ipod';}
- private members
- wrap in function
var name = 'ipod'
- privileged methods
this.getName = function () {return this.name};
- privacy failures
- if reference , can be changed
- solution
- make it small
- extend()&extendDeep()
- object literals and privacy
- prototypes and privacy
- to avoid private vars in constructor create every time
- .prototype = (function () {}());
- reveal private function as public method
myarray{isArray: isArray, indexOf: indexOf, inArray: indexOf}
- to avoid unexpectd happened
- if
myarray.isArray = null;
,the myarray.indexOf
still work
- if
- public
- modules create constructor
Constr.prototype = {constructor: MYAPP.utilities.Array,}; return Constr
- import globals into a module
- parameters
MYAPP.utilities.module = (function(myapp, global) {}(APP, this))
- parameters
- Namespace Pattern
- a global constructor
- new Sandbox()-->new constructor-->global namespace as parameter
- add modules
SandBox.module.dom = function(box) {box.getElement = function () {};}
- implement constructor
- force new
- args, callback , modules
- prototype
- name, version, getName
- a global constructor
- public
- constructor:
let Gadget = function () {};
- static member
Gadget.isShiny = function () {};
Gadget.setPrice === undefined
- normal method
Gadget.prototype.setPrice = function (price) { this.price = price};
Gadget.prototype.isShiny = function () {return Gadget.isShiny.call(this)}
- constructor:
- private
let Gadget = (function () { let conter = 0,new Gadget; return newGadget}
- singleton
- public
- Math.PI
- set(name, value)
- isDefined(name)
- get(name)
- return this
- Pros
- less type
- more specialized function
- Cons
- look up consumption
Function.prototype.method = function (name, implementation) {this.prototype[name] = implementation;return this;}
- classical
- Default Pattern
C.prototype = new P();
- Cons
- add own and prototype properties
- Rent a Constructor
function Child(a, c, b, d) {Parent.apply(this, arguments)}
- Cons
- no inherits from prototype
- Rent and Set Prototype
function Child(a, b, c, d) {Parent.apply(this, arguments);} Child.prototype = new Parent();
- Cons
- the parent called twice,(2 same names var exist)
- Share the Prototype
function inherit(C, P) { C.prototype = P.prototype;}
- Cons
- no Parent constructor properties
- Temporary Constructor
function inherit(C, P) {let F = function () {}; F.prototype = P.prototype; C.prototype = new F();C.uber = P.prototype; C.prototype.constructor = C}
- Default Pattern
- modern
- Klass
- prototypal inheritance
- inheritance by coping properties
- Mix-in
- borrow methods
- borrow from array
- borrow and bind
- Function.prototype.bind()
- classical
- use new
- instance in static propert
function Universe() {Universe.instance = this}
- instance in a closure
function Universe() {let instance = this; Universe = function () {return instance;}; Universe.prototype = this}
- CarMaker example
- Parent CarMaker constructor
- CarMaker.factory (static method)
create car objectCarMaker.factory = function(type)
- special constructor
CarMaker.Compact CarMaker.SUV, CarMaker.Convertible
- built-in Object Factory
- new Object(), new Object(1), new Object('1'), new Object(true)
- CarMaker example
- next
- hasNext
- rewind
- current
- enhance plain object
let sale = new Sale(100); sale.decorate('money');
- implementation
- single value
- with a list
- enhance plain object
- Data Validation Example
let myEvent = { stop: function (e) {e.stopPropogation();e.preventDefault()}}
- client<-->proxy<-->real object
- proxy as a cache
- colleague<-->mediator<-->colleague
- Example
- player 1
- player2
- Scoreborad
- Mediator(connect to player1 ,player2, scoreboard, keyboard)
- protect real object and loose coupling
- subscriber(oberver)
- publisher(subject)
- magazine subscript example
- publishier
- subscribers= []
- subscribe()
- unsubscribe()
- publish()
- publishier
- keypress game example
- publishier
- subscribers = []
- on
- remove
- fire
- publishier
- loose coupling by notify observer
- Content --> HTML
- Presentation --> CSS
- Behavior --> JS
- DOM Access
- Avoid DOM in loops
- Assigin DOM references in local
- Use selectors API
- Cache the length
- DOM Manipulation --> fewer DOM updates
- Fragment
let frag = document.createDocumentFragment();
frag.appendChild(...);
document.body.appendChild(frag)
- cloneNode(true)
let clone = oldnode.cloneNode(true);
true means deepcopyoldnode.parent.replaceChild(clone, oldnode)
- Fragment
- DOM Access
- Event Handle
- onclick()
- atachEvent()
- addEventLisener()
- Event Delegate
- one event listener for many events
- Event Handle
- setTimeout()
- web worker
let ww = new Worker('my_web_worker.js')
ww.onmessage = function (e) {e.data}
postMessage()
- XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleResponse;
xhr.readyState !==4 {return false}
(0-4 4 means completed)xhr.status !== 200{return false}
(200 = ok 404 = not found)
- xhr.open()
- GET/POST
- URL
- asynchronous(true)
- xhr.send('')
- GET-->""blank string
- POST-->data
- JSONP(tic-tac-toe)
- response of XHR
- XML documents
- HTML chunks
- JSON data
- Simple text file and others
- script
- script.src
- response of XHR
- Frame and Image Beacons
new Image().src =
script server
- XMLHttpRequest
- Combine Script
- less request to make all js files to one(all.js)
- 2parts
- core
- plugin
- Minify and compress
- Expires Header
- CDN
- Combine Script
- place
- HTTP chunking
- http1.1 supports load page chunkly
- <!-- end of chunk #1 -->
- dynamic
let mynamespace = {inline_script: []};
create as early page as possiblemynamespace.inline_script.push(function(){});
when need scriptfor (){script[i]()}
at last to loop
- append
let first_script = document.getElementsByTagName('script')
first_script.parentNode.insertBefore(script, first_script);
- lazy-loading
window.onload = function(){}
- loading on demand
- require(file, callback)
- preloading JavaScript
- in IE
- IE sniffing
if (/*@cc_on@*/false)
- Image
new Image().src = "preloadme.js"
- IE sniffing
- other
- create object
let obj = document.createElement('object');
- add data
obj.data = 'preloadme.js';
- obj.height,obj.weight = 0
- append to page
document.body.appendChild(obj)
- create object
- in IE