Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Basic JavaScript Coding Patterns

Ji Guang
November 09, 2012

Basic JavaScript Coding Patterns

no

Ji Guang

November 09, 2012
Tweet

More Decks by Ji Guang

Other Decks in Technology

Transcript

  1. Variable Definition  var a = 0, b=1, c=“xxx”; //

    shorter  var obj = {}; // faster  var arr = [];  var regex = /something/;
  2. Default Value  arg = arg || „default‟; // fallback

     e || e = window.event;  return a || „default‟
  3. Condition  answer = obj && obj.xx && obj.xx. property

     if( obj.xx ){ … } // don‟t: if(obj != null){}  if( a === b){ … } // always  if(document.getElementById){ … } // ability detect
  4. Ternary  check ? value1 : value2;  var foo

    = (condition) ? value1 : value2;  return (condition) ? value1 : value2;  foo = predicate ? ”one” :  predicate ? ”two” :  ”default”;
  5. DOM Operation  el.style.display = „none‟; // offline  //

    operation  el.style.display = „block‟;  var fragment = document.createDocumentFragment();  innerHTML  // Be careful with NodeList  var imges = document.getElementsByTagName(„img‟);
  6. Event Agent  attach event at a higher level 

    <div id=“highLevelElement”>  <div><ul><li> … </li></ul></div>  </div>  $(„#id‟).click(function(evt){ … });
  7. Object as a Namespace  var MYAPP = {}; 

    MYAPP.namespace(„event‟);
  8. Chaining  var obj = new MYAPP.dom.Element(„span‟);  obj.setText(„hello‟) 

    .setStyle(„color‟, „red‟)  .serStyle(„font‟, „Verdana‟);  document.body.appendChild(obj);  // return this
  9. Configure Obj  function foo( conf ){ … } 

    foo ({  key1 : 1,  key2 : 2  })
  10. Type Conversion  +‟010‟ === 10  Number(„010‟) === 10

     parseInt(„010‟, 10) === 10  10 + “” === “10”
  11. Loop  for ( var I = 0, j =

    xx.length; i<j; i++){ … } // cache  var I = 0, j = xx.lenght;  for (;i<j; i++){ … } // hoisting  for ( var I in foo ){  if( foo.hasOwnProperty(i) ){ // required  console.log(i)  }  }
  12. New Feature  Array.forEach() // use it when possible 

    getElementsByClassName()  querySlectorAll()
  13. Lazy Definition  function lazyDef(){  if(condition1){  lazyDef =

    function(){ … };  }else if(condition2){  lazyDef = function(){ … };  }  return lazyDef();  }
  14. Private Functions as Public Methods  var MYAPP = {};

     MYAPP.dom = (function(){  var _setStyle = function(el, prop, value){  console.log(„setStyle‟);  };  return {  setStyle: _setStyle  };  })(); // MYAPP.dom.setStyle = otherFunc