Skip to content

JiangLiruii/JavaScript_Pattern

Repository files navigation

This is outline and code resource for JavaScript_Pattern book

more detail and better format click here

  • JavascriptPattern
    • Chapter1 Introduction

      • Patterns

        • design pattern
        • coding pattern
        • Antipattern
          • problems > sloves
      • JavaScript: Concepts

        • Object-Oriented
        • No Classes
        • Prototypes
        • Enviroment(browser)
          • provide host object
      • ECMAScript 5

      • JSLint

      • The Console

        • console.log
        • console.dir
    • Chapter2 Essentials

      • Maintainable Code

      • Minimizing Globals

        • problem
        • forget var
        • access to global
        • single var pattern
        • hoisting
      • For Loops

        • DOM
        • .length
        • single var pattern
        • ++ to += 1
      • For-in Loops

        • .hasOwnProperty()
      • Switch Pattern

        • case + break
        • endswith default
      • Avoid Implied Typecasting

        • 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
      • Convert To Number

        • parseInt("08 hello")
        • Number("08")
        • + "08"
      • Code Conversions

        • 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 variablesfor (let i = 0, max = myarray.length; i < max; i ++){...}
            • after ',' in array arr = [1, 2, 3]
            • after object propertieslet o = {a: 1, b: 2}
            • function argumentsfunction(a, b, c)
            • before and after '{'function foo() {...}
            • anonymous functionlet foo = function () {}
            • operators+ - * / < > <= >= === !== && || +=
            • blank line for seperate unite
      • Name Conventions

        • upper camel constructor(able to new)function MyConstructor(){...}
        • lower camel functionfunction myFunction() {}
        • lowercase and underscore variables my_name
        • Capital Name for constant or global variables let PI = 3.14
        • underscore first private member _getScore(){...}
      • Write Comments

      • Write API Docs

        • SDK(software developer kit)
        • YUIDoc(Yahoo!User Interface)
        • /*/
    • Chapter3 Literals and Constructors

      • Object Literal

        • Object literal {} no new Object(Number,String)
      • Object from a constructor

        • build-in(Array,Number,String)
        • custome constructor
          • invoke with new
          • customer return value(without inheritant properties, and lose this prototype)
      • Patterns for Enforcing new
        if (this instanceof obj) {return new obj}

        • pollute global(this-->global)
        • Self-Invoke Constructor
      • Array Literal

        • []
        • new Array(.length) new Array(3) = ['undefined', 'undefined', 'undefined']
      • JSON

        • parse json: JSON.parse()
        • opp: JSON.stringify()
      • RegExp

        • i/g/m
        • /rules/igm
      • Primitive Wrapper

        • number, string, boolean, (null, undefined: without constructor)
        • avoid new String Number Boolean
          • properties cannot augment
          • Error(throw{name:..., message...}
    • Chapter4 Functions

      • Background

        • Disambiguation of Teminology
          • named function let foo = function foo() {}
          • unnamed functionlet foo = function () {}
            • foo.name = ''
          • function declarationfunction foo() {}
        • Declarations Versus Expressions: Names and Hoisting
        • Function's name Property
        • Function Hoisting
          • delaration hoist both name('foo') and implementation
      • API Pattern

        • 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
      • Initialization 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)
      • Performance patterns

        • 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
    • Chapter5 Object creation pattern

      • Module Pattern

        • 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
        • 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))
      • Sandbox 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
      • Static Members(don't change)

        • 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)}
        • private
          • let Gadget = (function () { let conter = 0,new Gadget; return newGadget}
          • singleton
      • Object Constants

        • Math.PI
        • set(name, value)
        • isDefined(name)
        • get(name)
      • Chaining Pattern

        • return this
        • Pros
          • less type
          • more specialized function
        • Cons
          • look up consumption
      • method() Method

        • Function.prototype.method = function (name, implementation) {this.prototype[name] = implementation;return this;}
    • Chapter6 Code Reuse Pattern

      • inheritance

        • 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}
        • modern
          • Klass
          • prototypal inheritance
          • inheritance by coping properties
          • Mix-in
          • borrow methods
            • borrow from array
            • borrow and bind
            • Function.prototype.bind()
    • Chapter7 Design Pattern

      • Singleton

        • 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}
      • Factory

        • 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)
      • Iterator

        • next
        • hasNext
        • rewind
        • current
      • Decorator

        • enhance plain object
          let sale = new Sale(100); sale.decorate('money');
        • implementation
          • single value
          • with a list
      • Strategy

        • Data Validation Example
      • Facade

        • let myEvent = { stop: function (e) {e.stopPropogation();e.preventDefault()}}
      • Proxy

        • client<-->proxy<-->real object
        • proxy as a cache
      • Mediator

        • colleague<-->mediator<-->colleague
        • Example
          • player 1
          • player2
          • Scoreborad
          • Mediator(connect to player1 ,player2, scoreboard, keyboard)
        • protect real object and loose coupling
      • Observe

        • subscriber(oberver)
        • publisher(subject)
        • magazine subscript example
          • publishier
            • subscribers= []
            • subscribe()
            • unsubscribe()
            • publish()
        • keypress game example
          • publishier
            • subscribers = []
            • on
            • remove
            • fire
        • loose coupling by notify observer
    • Chapter 8 DOM and Browser Patterns

      • Seperation Content

        • Content --> HTML
        • Presentation --> CSS
        • Behavior --> JS
      • DOM script

        • 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 deepcopy
            • oldnode.parent.replaceChild(clone, oldnode)
      • Event

        • Event Handle
          • onclick()
          • atachEvent()
          • addEventLisener()
        • Event Delegate
          • one event listener for many events
      • Long-Running Script

        • setTimeout()
        • web worker
          • let ww = new Worker('my_web_worker.js')
          • ww.onmessage = function (e) {e.data}
          • postMessage()
      • Remote Scripting

        • 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
        • Frame and Image Beacons
          • new Image().src =script server
      • Deploy Javascript

        • Combine Script
          • less request to make all js files to one(all.js)
          • 2parts
            • core
            • plugin
        • Minify and compress
        • Expires Header
        • CDN
      • Load Strategy

        • place
        • HTTP chunking
          • http1.1 supports load page chunkly
          • <!-- end of chunk #1 -->
        • dynamic
          • let mynamespace = {inline_script: []};create as early page as possible
          • mynamespace.inline_script.push(function(){});when need script
          • for (){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"
          • other
            • create objectlet obj = document.createElement('object');
            • add data obj.data = 'preloadme.js';
            • obj.height,obj.weight = 0
            • append to pagedocument.body.appendChild(obj)
Edit By Lorry Jiang

About

No description or website provided.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published