Skip to content

Instantly share code, notes, and snippets.

@samoshkin
Created May 15, 2012 20: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 samoshkin/2704886 to your computer and use it in GitHub Desktop.
Save samoshkin/2704886 to your computer and use it in GitHub Desktop.
Creating method overloads in JS using Function.length
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 );
};
}
@samoshkin
Copy link
Author

Original source:
Learning Advanced JavaScript - http://ejohn.org/apps/learn/#89

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment