Last active
August 26, 2016 11:06
-
-
Save dmail/6e639ac50cec8074a346c9e10e76fa65 to your computer and use it in GitHub Desktop.
JavaScript Function cloning implementation and documentation
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
function cloneFunction(fn, mode = 'primitive') { | |
var clonedFn; | |
if (mode === 'primitive') { | |
clonedFn = fn; | |
} else if (mode === 'construct') { | |
clonedFn = new Function('return ' + fn.toString())(); | |
} else if (mode === 'wrap') { | |
let Constructor; | |
clonedFn = function() { | |
if (this instanceof clonedFn) { | |
// some native constructor must absolutely be called using new (Array for instance) | |
// se we can't use Object.create but we need to be able to pass arbitrary number of arguments | |
// http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible | |
if (Constructor === undefined) { | |
Constructor = function(args) { | |
return fn.apply(this, args); | |
}; | |
Constructor.prototype = fn.prototype; | |
} | |
return new Constructor(arguments); | |
} | |
return fn.apply(this, arguments); | |
}; | |
} else if (mode === 'bind') { | |
clonedFn = fn.bind(arguments[2]); | |
} | |
return clonedFn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Every mode has a subset of the following features :
clonedFn
can have its own properties (not shared with fn).clonedFn
have access to fn scope.clonedFn
involves only one function call.clonedFn
can have its own this