Created
July 11, 2010 02:39
-
-
Save jeffgca/471222 to your computer and use it in GitHub Desktop.
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
/* Funky JavaScript patterns from Resig's talk @ VanJS in Vancouver today. */ | |
/* url: http://ejohn.org/apps/learn/bind.html */ | |
/* loop => callback construct utilizing .call() for each member of the input array */ | |
function loop(array, fn){ | |
for ( var i = 0; i < array.length; i++ ) { | |
fn.call(array, array[i], i); | |
} | |
} | |
var num = 0; | |
loop([0, 1, 2], function(value, i){ | |
assert(value == num++, | |
"Make sure the contents are as we expect it."); | |
assert(this instanceof Array, | |
"The context should be the full array."); | |
}); | |
/* | |
potentially more convenient instantiation | |
this way you never have to do x = new y(); | |
*/ | |
function User(first, last){ | |
if ( !(this instanceof User) ) | |
return new User(first, last); | |
this.name = first + " " + last; | |
} | |
var u = User(); // <-- instance of user!! | |
/* pattern for co-ercing the arguments object into an array */ | |
var x = function() { | |
var args = Array.prototype.slice.call(args); | |
} | |
// pattern for or ( || ) operator comparison: | |
var something = foo || /* OR */ bar; | |
var something = false || 0; // FALSE | |
var something = false || 1; // 1!! | |
var something = -12 || 1; // -12 !!!! | |
/* for loop that calls a closure function with an argument from the loop. */ | |
for ( var d = 0; d < 3; d++ ) (function(d){ | |
setTimeout(function(){ | |
log( "Value of d: ", d ); | |
assert( d == d, "Check the value of d." ); | |
}, d * 200); | |
})(d); | |
/* resig's assert function */ | |
function assert(pass, msg){ | |
var type = pass ? "PASS" : "FAIL"; | |
jQuery("#results").append("<li class='" + type + "'><b>" + type + "</b> " + msg + "</li>"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment