JavaScript: Patterns, Part 2


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

JavaScript: Patterns, Part 2

  1. 1. JavaScript Patterns Part Two
  2. 2. Error ObjectsBuilt-ins you can throw ● Error, SyntaxError, TypeError, RangeError, etc. ● can be used with or without newAll have properties ● name - of constructor ● message - string passed in constructor ● and others that are not universally supportedYou can throw any object ● add name and message to be consistent ● plus any other properties you want ● preferred method
  3. 3. The consoleUse FireBug CommandEditor to experimentLOG outputs tracesconsole.log("test", 1, {}, [1,2,3]);DIR outputs enumerationsconsole.dir({one:1, two: {three: 3}}); === window[name];
  4. 4. Minimizing Globalsmyglobal = "hello"; ● makes a property on windowconsole.log(myglobal); ● the global this is impliedconsole.log(window.myglobal);console.log(window[myglobal]);console.log(this.myglobal);
  5. 5. Implied GlobalsAny variable you dont declare with var becomes property of globalthis is badfunction sum(x,y){result = x+y;return result;}this is goodfunction sum(x,y){var result = x+y;return result;}
  6. 6. Implied Globals (cont.)Implied globals are not real variables, rather properties of the global objectthis is badfunction foo(){var a = b = 0;}this is goodfunction foo(){var a, b;a = b = 0;}
  7. 7. DeleteGlobal variables, created with var, cannot be deletedGlobal properties (declared without var) can be deletedIn general ● properties can be deleted ● variables can not be deleted
  8. 8. Accessing global objectfrom anywhere via window*dont EVER declare a local var using the word windowto access global without using window you can do the following fromanywhere, any level of nested scope:....(){ var G = (function(){ return this; }());
  9. 9. Single var patternsingle place to look for all local variablesprevents logical errors: when a var is used before its definedhelps minimize globals/implied globalsless code to write - only 1 var statementcan initialize if you want to
  10. 10. Single var pattern (cont.)another good example of doing work in single varcan initialize and chainfunction updateElement(){ var element = document.getElementById("result"), style =;}
  11. 11. Variable Hoistingyou can put a var statement anywhere in a functionbut you shouldntall vars will all act as if they were declared at top of function
  12. 12. Loopsoptimizing forleast optimal:for(var i = 0; i < myarray.length; i++){}especially bad for dom collections since they are live querieswhich are very expensivebetter:for(var i = 0, max = myarray.length; i < max; i++){}
  13. 13. Loops (cont.)for in enumerationuse hasOwnProperty() to filter out the prototype propertiescall it from the object you are iterating overORfrom 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. 14. TypesThere are 5 primitives: 1. number 2. string 3. boolean 4. null 5. undefinedPrimitives are NOT objects ○ no properties ○ no methods ○ however....there is temporary conversionLiterals are not necessarily primitives ● { } and [ ] are literals - not primitives ● "s", true, 3 are literals - are primitives
  15. 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 fasterbut not be able to handle compound stringslike "08 hello"
  16. 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 classesconstructors can be deceitful ● new Object("hello") creates an object using the String constructor
  17. 17. Primitivesdifference between number primitive and Number wrapper objectthe primitive object wrappers have some useful functions,but the literals are converted at runtimeif you need to augment the value and persist state, then use the wrapper -primitives can not do thiswrappers without new can be used to convert values to primitives