Last active
December 17, 2015 08:49
-
-
Save beaspider/5583003 to your computer and use it in GitHub Desktop.
Common JS Patterns & Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// standard closure / setup code | |
// either pass in browser standard objects | |
(function (win, doc) { | |
'use strict'; | |
})(window, document); | |
// or just leave alone | |
(function(){ | |
// `window` in the browser, `exports` on the server | |
var root = this; | |
// just a reminder that until ECMAScript 5 when you create an object `this` loses scope | |
// in nested functions.... | |
var something = { | |
function() { | |
var self = this; | |
// this === something | |
function() { | |
// this === root; | |
// but we can access self :) | |
} | |
} | |
} | |
// lightweight log wrapper see // http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ | |
// usage: log('inside coolFunc',this,arguments); | |
this.log = function(){ | |
log.history = log.history || []; // store logs to an array for reference | |
log.history.push(arguments); | |
if(this.console){ | |
console.log( Array.prototype.slice.call(arguments) ); | |
} | |
}; | |
}).call(this); | |
// end of our closure / setup code | |
// for loop | |
var stuff = [1,2,3] | |
for (var i=0,z=stuff.length;i<z;i++) { | |
console.log("i=" + stuff[i]); | |
} | |
// switch | |
switch(n) { | |
case 1: | |
console.log("n should be 1, n =" + n); | |
break; | |
case 2: | |
console.log("n should be 2, n =" + n); | |
break; | |
default: | |
console.log("n should not be 1 or 2, n =" + n); | |
} | |
// while | |
var i = 0; | |
while (i<3) { | |
console.log("i=" +i); | |
} | |
// objects |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment