In JavaScript, how do I clone a function? Or, how to clone a function's parameter list and function body to a new function? In JavaScript, how do I clone a function?
Or, how to clone a function's parameter list and function body to a new function?
For example, if a Function. prototype. clone method is used to clone a Function, the usage is as follows:
var original = function original_name(a, b) { return a + b; }; var cloned = original.clone(); alert(cloned == original); //false
A new function is a completely new object. It has its own scope, but its usage is exactly the same as that of the original function.
First, you will surely think of using eval. eval can be said to be a great devil.
You only need a few lines of code to achieve this:
Function.prototype.clone = function(){ var func; eval("func = " + this.toString()); return func; };
Since eval can work, its brother functions can certainly do the same:
Function.prototype.clone = function(){ return new Function("return " + this.toString())(); };
This line of code is even more incisive, but Function usage is not a new solution:
String.prototype.trim = function(){ return this.replace(/(^\s*)|(\s*$)/g, ""); }; Function.prototype.clone = function() { var findArgs = function(funcStr){ var bracket1 = funcStr.indexOf("("); var bracket2 = funcStr.indexOf(")"); var argsStr = funcStr.slice(bracket1+1,bracket2); var args = argsStr.split(","); return args.map(function(e){ return e.trim(); }); }; var funcStr = this.toString(); var args = findArgs(funcStr); var bigBracket1 = funcStr.indexOf("{"); var bigBracket2 = funcStr.lastIndexOf("}"); var body = funcStr.slice(bigBracket1+1,bigBracket2); args.push(body); return Function.apply(null,args); };
This method uses the features of the Function to obtain the original Function string, intercept the parameter list, and inject the Function call in sequence.
This truncation process can be written using regular expressions to make the code more concise.
The above is JavaScript fun: The content of function cloning. For more information, see PHP Chinese website (www.php1.cn )!