Skip to content

Instantly share code, notes, and snippets.

@freethejazz
Last active December 29, 2015 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freethejazz/7608349 to your computer and use it in GitHub Desktop.
Save freethejazz/7608349 to your computer and use it in GitHub Desktop.
Examples from my InfoWorld article(http://www.infoworld.com/d/application-development/6-secrets-of-javascript-jedis-231322), indented properly.
/**********************
* Here are the code snippets from my InfoWorld article
* on JavaScript, properly formatted. Original article
* can be found here:
*
* http://www.infoworld.com/d/application-development/6-secrets-of-javascript-jedis-231322
*
**********************/
// ** Closures **
function makeThreeTimer(){
var count = 0;
return function(){
if(count < 3){
console.log('doing work');
count++;
}
else {
throw new Error('No more work');
}
}
}
var threeTimer = makeThreeTimer();
threeTimer(); // logs ‘doing work’ (count gets incremented)
threeTimer(); // logs ‘doing work’ (count gets incremented)
threeTimer(); // logs ‘doing work’ (count gets incremented)
threeTimer(); // throws an error
threeTimer.count; // returns undefined
// ** Invoking Functions **
// Possible implementation of bind using apply
function bind(func, context){
return function(){
func.apply(context, Array.prototype.slice.apply(arguments));
}
}
// ** What's This**
Person.getName(); // ‘this’ points to Person
setTimeout(Person.getName, 1000); // ‘this’ points to the global object
// **Namespacing**
// The global footprint is a single object containing
// all other references needed.
var MyApp = {};
MyApp.id = 42;
MyApp.utils = {
validate: function(){
//do work
}
};
//or the module pattern:
// **Module pattern**
// This relies on immediately-invoked anonymous functions and the
// closure they create to maintain access to variables within the
// function.
var MyApp = (function(){
//declare a local variable
var appId = 42;
function getAppId(){
//referring to a variable in this function’s parent scope
return appId;
}
return {
getAppId: getAppId
};
}());
appId; // undefined
MyApp.appId; //undefined
MyApp.getAppId(); // returns 42. (Brought to you by closures)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment