KEMBAR78
JavaScript: Patterns, Part 2 | PDF
JavaScript Patterns

      Part Two
Error Objects


Built-in's you can throw
 ● Error, SyntaxError, TypeError, RangeError, etc.
 ● can be used with or without 'new'


All have properties
 ● name - of constructor
 ● message - string passed in constructor
 ● and others that are not universally supported


You can 'throw' any object
 ● add 'name' and 'message' to be consistent
 ● plus any other properties you want
 ● preferred method
The console


Use FireBug CommandEditor to experiment

LOG outputs traces
console.log("test", 1, {}, [1,2,3]);


DIR outputs enumerations
console.dir({one:1, two: {three: 3}});


ACCESS
window.name === window['name'];
Minimizing Globals


myglobal = "hello";
 ● makes a property on window


console.log(myglobal);
 ● the global 'this' is implied


console.log(window.myglobal);


console.log(window['myglobal']);


console.log(this.myglobal);
Implied Globals


Any variable you don't declare with var becomes property of global


this is bad
function sum(x,y){
result = x+y;
return result;
}


this is good
function sum(x,y){
var result = x+y;
return result;
}
Implied Globals (cont.)


Implied globals are not real variables, rather properties of the global object


this is bad
function foo(){
var a = b = 0;
}


this is good
function foo(){
var a, b;
a = b = 0;
}
Delete


Global variables, created with var, cannot be deleted


Global properties (declared without var) can be deleted


In general
  ● properties can be deleted
  ● variables can not be deleted
Accessing global object


from anywhere via 'window'


*don't EVER declare a local var using the word 'window'


to access global without using 'window' you can do the following from
anywhere, any level of nested scope:


....(){
    var G = (function(){
        return this;
    }());
Single var pattern


single place to look for all local variables


prevents logical errors: when a var is used before it's defined


helps minimize globals/implied globals


less code to write - only 1 'var' statement


can initialize if you want to
Single var pattern (cont.)


another good example of doing work in single var


can initialize and chain


function updateElement(){
  var element = document.getElementById("result"),
       style = element.style;
}
Variable Hoisting


you can put a 'var' statement anywhere in a function


but you shouldn't


all vars will all act as if they were declared at top of function
Loops


optimizing 'for'


least optimal:
for(var i = 0; i < myarray.length; i++){}


especially bad for dom collections since they are live queries
which are very expensive


better:
for(var i = 0, max = myarray.length; i < max; i++){}
Loops (cont.)


'for in' enumeration


use hasOwnProperty() to filter out the prototype properties


call it from the object you are iterating over
OR
from the prototype of Object
  ● avoids collisions with any redefinition of hasOwnProperty
  ● cached version of this can avoid an iterative long   property lookup
    all the way up the prototype chain
Types

There are 5 primitives:
    1. number
    2. string
    3. boolean
    4. null
    5. undefined


Primitives are NOT objects
     ○ no properties
     ○ no methods
     ○ however....there is temporary conversion


Literals are not necessarily primitives
  ● { } and [ ] are literals - not primitives
  ● "s", true, 3 are literals - are primitives
Types (cont.)


conversion


   ● parseInt(string, radix)
      ○ converts a string to a number
      ○ do not leave out the radix!
          ■ strings that begin with '0' are treated as octal
      ○ there are other ways to convert a string that are faster
but not be able to handle compound strings
like "08 hello"
Literals


{}, [], "", 3, true , / /


advantages over the built-in constructors
 ● more concise
 ● more expressive
 ● less error-prone
 ● emphasizes the fact that objects are mutable hashes, not classes


constructors can be deceitful
 ● new Object("hello") creates an object using the String constructor
Primitives


difference between number primitive and Number wrapper object


the primitive object wrappers have some useful functions,
but the literals are converted at runtime


if you need to augment the value and persist state, then use the wrapper -
primitives can not do this


wrappers without 'new' can be used to convert values to primitives

JavaScript: Patterns, Part 2

  • 1.
  • 2.
    Error Objects Built-in's youcan throw ● Error, SyntaxError, TypeError, RangeError, etc. ● can be used with or without 'new' All have properties ● name - of constructor ● message - string passed in constructor ● and others that are not universally supported You can 'throw' any object ● add 'name' and 'message' to be consistent ● plus any other properties you want ● preferred method
  • 3.
    The console Use FireBugCommandEditor to experiment LOG outputs traces console.log("test", 1, {}, [1,2,3]); DIR outputs enumerations console.dir({one:1, two: {three: 3}}); ACCESS window.name === window['name'];
  • 4.
    Minimizing Globals myglobal ="hello"; ● makes a property on window console.log(myglobal); ● the global 'this' is implied console.log(window.myglobal); console.log(window['myglobal']); console.log(this.myglobal);
  • 5.
    Implied Globals Any variableyou don't declare with var becomes property of global this is bad function sum(x,y){ result = x+y; return result; } this is good function sum(x,y){ var result = x+y; return result; }
  • 6.
    Implied Globals (cont.) Impliedglobals are not real variables, rather properties of the global object this is bad function foo(){ var a = b = 0; } this is good function foo(){ var a, b; a = b = 0; }
  • 7.
    Delete Global variables, createdwith var, cannot be deleted Global properties (declared without var) can be deleted In general ● properties can be deleted ● variables can not be deleted
  • 8.
    Accessing global object fromanywhere via 'window' *don't EVER declare a local var using the word 'window' to access global without using 'window' you can do the following from anywhere, any level of nested scope: ....(){ var G = (function(){ return this; }());
  • 9.
    Single var pattern singleplace to look for all local variables prevents logical errors: when a var is used before it's defined helps minimize globals/implied globals less code to write - only 1 'var' statement can initialize if you want to
  • 10.
    Single var pattern(cont.) another good example of doing work in single var can initialize and chain function updateElement(){ var element = document.getElementById("result"), style = element.style; }
  • 11.
    Variable Hoisting you canput a 'var' statement anywhere in a function but you shouldn't all vars will all act as if they were declared at top of function
  • 12.
    Loops optimizing 'for' least optimal: for(vari = 0; i < myarray.length; i++){} especially bad for dom collections since they are live queries which are very expensive better: for(var i = 0, max = myarray.length; i < max; i++){}
  • 13.
    Loops (cont.) 'for in'enumeration use hasOwnProperty() to filter out the prototype properties call it from the object you are iterating over OR from the prototype of Object ● avoids collisions with any redefinition of hasOwnProperty ● cached version of this can avoid an iterative long property lookup all the way up the prototype chain
  • 14.
    Types There are 5primitives: 1. number 2. string 3. boolean 4. null 5. undefined Primitives are NOT objects ○ no properties ○ no methods ○ however....there is temporary conversion Literals are not necessarily primitives ● { } and [ ] are literals - not primitives ● "s", true, 3 are literals - are primitives
  • 15.
    Types (cont.) conversion ● parseInt(string, radix) ○ converts a string to a number ○ do not leave out the radix! ■ strings that begin with '0' are treated as octal ○ there are other ways to convert a string that are faster but not be able to handle compound strings like "08 hello"
  • 16.
    Literals {}, [], "",3, true , / / advantages over the built-in constructors ● more concise ● more expressive ● less error-prone ● emphasizes the fact that objects are mutable hashes, not classes constructors can be deceitful ● new Object("hello") creates an object using the String constructor
  • 17.
    Primitives difference between numberprimitive and Number wrapper object the primitive object wrappers have some useful functions, but the literals are converted at runtime if you need to augment the value and persist state, then use the wrapper - primitives can not do this wrappers without 'new' can be used to convert values to primitives