Created
March 29, 2014 08:08
-
-
Save wonglok/9850563 to your computer and use it in GitHub Desktop.
Overloading Closure
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
http://ejohn.org/apps/learn/#90 | |
function assert(pass, msg){ | |
var type = pass ? "PASS" : "FAIL"; | |
jQuery("#results").append("<li class='" + type + "'><b>" + type + "</b> " + msg + "</li>"); | |
} | |
function addMethod(object, name, fn){ | |
// Save a reference to the old method | |
// that is a closure that has access to older func args | |
// This is like a recursive action.... | |
var old = object[ name ]; | |
//this elegantly create new *closures* every thing calls this function.... | |
//when calling this helper | |
//if not used correctly/abusive | |
//is a memory leak. | |
// Overwrite the method with our new one | |
object[ name ] = function(){ | |
// Check the number of incoming arguments, | |
// compared to our overloaded function | |
function meetAllRules(args){ | |
return fn.length == args.length; | |
} | |
if (meetAllRules(arguments)) | |
// If there was a match, run the function | |
return fn.apply( this, arguments ); | |
// Otherwise, fallback to the old method | |
else if ( typeof old === "function" ) | |
return old.apply( this, arguments ); | |
else | |
console.log('cannot resolve....') | |
}; | |
} | |
function Ninjas(){ | |
var ninjas = [ "Dean Edwards", "Sam Stephenson", "Alex Russell" ]; | |
addMethod(this, "find", function(){ | |
return ninjas; | |
}); | |
addMethod(this, "find", function(name){ | |
var ret = []; | |
for ( var i = 0; i < ninjas.length; i++ ) | |
if ( ninjas[i].indexOf(name) == 0 ) | |
ret.push( ninjas[i] ); | |
return ret; | |
}); | |
addMethod(this, "find", function(first, last){ | |
var ret = []; | |
for ( var i = 0; i < ninjas.length; i++ ) | |
if ( ninjas[i] == (first + " " + last) ) | |
ret.push( ninjas[i] ); | |
return ret; | |
}); | |
} | |
var ninjas = new Ninjas(); | |
assert( ninjas.find().length == 3, "Finds all ninjas" ); | |
assert( ninjas.find("Sam").length == 1, "Finds ninjas by first name" ); | |
assert( ninjas.find("Dean", "Edwards").length == 1, "Finds ninjas by first and last name" ); | |
assert( ninjas.find("Alex", "X", "Russell") == null, "Does nothing" ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment