Created
August 31, 2013 12:33
-
-
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".
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 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