Created
May 15, 2012 20:29
-
-
Save samoshkin/2704886 to your computer and use it in GitHub Desktop.
Creating method overloads in JS using Function.length
This file contains hidden or 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
function addMethod(object, name, fn){ | |
// Save a reference to the old method | |
var old = object[ name ]; | |
// Overwrite the method with our new one | |
object[ name ] = function(){ | |
// Check the number of incoming arguments, | |
// compared to our overloaded function | |
if ( fn.length == arguments.length ) | |
// 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 ); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original source:
Learning Advanced JavaScript - http://ejohn.org/apps/learn/#89