Skip to content

Instantly share code, notes, and snippets.

@ahultgren
Created August 31, 2013 12:33
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 ahultgren/6397920 to your computer and use it in GitHub Desktop.
Save ahultgren/6397920 to your computer and use it in GitHub Desktop.
Clone a function. Creates a new function that is exactly the same as the original, but without its properties. Essential if you want to construct a "callable object".
function cloneFn (fn) {
var args,
strFn = fn.toString();
// Extract argument names
// Match first occurence of "(<anything but end-parenthesis>)",
// split it on "," and use as args
args = [Function].concat(strFn
.match(/\(([^\)]*)\)/)[1]
.trim()
.split(/\s*,\s*/)
.filter(Boolean));
// Extract function body
// Find first "{" and last "}" and grab everything inbetween
args.push(strFn.substring(strFn.indexOf('{') + 1, strFn.lastIndexOf('}')));
// Create and return the new function
return new (Function.bind.apply(Function, args))();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment