document.onkeydown=function(e){//return the right event e=e||window.event;//get keycodevarkeyCode=e.keyCode||e.which;}
6. Code Convention for Module Pattern Component
// the typical anatomy of a component component.init( config ) // initialisation - accepts JSON for configuration options component.init// intialisation (optional self invoking), can be used pass through, unload, onDomReady or arbitrarily component.addEvents// event handlingcomponent.display// display component.destroy// remove component and clean up reference onunload
7. Annonymous Immediately Invoking Function (IFF)
// avoid global scope// create a new annonymous function, to use as a wrapper// from Pro JavaScript Techniques By John Resig(function(){// The variable that would, normally, be globalvarmsg="Thanks for visiting!";// Binding a new function to a global objectwindow.onload=function(){// Which uses the 'hidden' variablealert(msg);};// Close off the annonymous function and execute it })();
varperson={drinkBeer : function(){alert("drinking...");},burp : function(){alert("burping...");},purge : function(){alert("purging...");}};// alsoperson.drinkBeer();// orperson["drinkBeer"]();// this could be a dynamic variable altered at runtimevarmethodCall="drinkBeer";// call the relevant method person[methodCall]();
11. Front End Performance Tip for string concatenation
varstuckTogether=["value1","value2","value3"].join("");// Deprecated: use concat instead (see #34)
12. Module Pattern (public and private members within a namespace)
jQuery.noConflict()//Note: ; before parenthesis is deliberate;(function(container,document,$,undefined){// add in more parameters for context e.g. ( container, document, jQuery, utils ), pass in undefined so it can't be re-assigned (security)functioncreateModule(){// Revealing Module Pattern with execution context passed in argumentsvarlocalVariable="local variable",myPublicProperty="public variable",init=function(){}();// self invokingfunctionmyPrivateMethod(){// not in contract list so remains private}// end myPrivateMethodfunctionmyPublicMethod(){return"public function";}// end myPublicMethodvarcontract={myPublicProperty : myPublicProperty,myPublicMethod : myPublicMethod}// Public interface (properties and methods)returncontract;}// end module// Public API (assigns to my namespace)container.ModuleName=createModule();})(window.mynamespace||(window.mynamespace={}),jQuery,document);//end mynamespace.ModuleName (create namespace and context)
13. Multi Line Alternative to String Concatenation
// careful using this with some build tools varmyString="some really long text repeated\n\ some really long text repeated\n\ some really long text repeated";
14. Faster Loops
varitemsLen=items.length;// cache length - prevents evaluation on each loopfor(i=itemsLen;i--;){// looping backwards is faster//note: loop works in reverse}
functionsupports_canvas(){return!!document.createElement('canvas').getContext;}/*if getContext gives you a "falsey" value, the !! will make it return the boolean value false. Otherwise it will return true.The "falsey" values are:falseNaNundefinednull"" (empty string)0*/
19. Append an Array to Another Array
vara=[4,5,6];varb=[7,8,9];Array.prototype.push.apply(a,b);console.log(a);// is: [4, 5, 6, 7, 8, 9]
varlist=[1,2,3,4,5,6,7,8,9];list=list.sort(function(){returnMath.random()-0.5});console.log(list);// prints something like: 4,3,1,2,9,5,6,7,8
22. SyntaxError (JavaScript 1.5)
// raised when a syntax error occurs while parsing code in eval()try{eval('1 + * 5');// will rise a SyntaxError exception}catch(ex){console.log(ex.constructor==SyntaxError);// Prints true}// JavaScript 1.7try{eval('1 + * 5');}catch(exifexinstanceofSyntaxError){console.log('SyntaxError !');// prints: SyntaxError !}
23. Function Hijacking
varobj={// static object // add function, supports adding 2 values add: function(x,y){returnx+y;}};// move the existing function to another variable name obj.__add=obj.add;// override the existing function with your own, to support adding 2 or 3 values obj.add=function(x,y,z){varval=obj.__add(x,y);returnz ? val+z : val;}
// define the Person Class functionPerson(){}Person.prototype.walk=function(){alert('I am walking!');};Person.prototype.sayHello=function(){alert('hello');};// define the Student class functionStudent(){// Call the parent constructor Person.call(this);}// inherit Person Student.prototype=newPerson();// correct the constructor pointer because it points to Person Student.prototype.constructor=Student;// replace the sayHello method Student.prototype.sayHello=function(){alert('hi, I am a student');}// add sayGoodBye method Student.prototype.sayGoodBye=function(){alert('goodBye');}varstudent1=newStudent();student1.sayHello();student1.walk();student1.sayGoodBye();// check inheritance alert(student1instanceofPerson);// true alert(student1instanceofStudent);// true
// This example requires the script engine to create 21 new string objects, once for each time the length property is accessed, and once each time the charAt method is called:vars='0123456789';for(vari=0;i<s.length;i++){s.charAt(i);}// This equivalent example creates just a single object, and will perform better as a result:vars=newString('0123456789');for(vari=0;i<s.length;i++){s.charAt(i);}
arr=1// That's a simple integer, of course.Object.prototype.toString.call(arr)=='[object Array]';// falsearr='1'// Just a string.Object.prototype.toString.call(arr)=='[object Array]';// falsearr='[1,2,3]'// Also a string.Object.prototype.toString.call(arr)=='[object Array]';// falsearr={x:1,y:2}// That's an object, no array either!Object.prototype.toString.call(arr)=='[object Array]';// falsearr=[1,2,3]// An array, so it should be true.Object.prototype.toString.call(arr)=='[object Array]';// true
// ok (iterate over all and return a new array)
const user = users.filter(u => u.id === id)[0];
// better (find first one and stop)
const user = users.find(u => u.id === id);
// example 1
let myString = (() => {/*
<div id="someId">
some content<br />
<a href="#someRef">someRefTxt</a>
</div>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]
// example 2
let tennysonQuote = (() => {/*
Theirs not to make reply,
Theirs not to reason why,
Theirs but to do and die
*/}).toString().replace(/^[^\/]+\/\*!?/, '').replace(/\*\/[^\/]+$/, '')
45 JavaScript Base64 runtime payload using ES6 template literals