Home  >  Article  >  Web Front-end  >  JavaScript Fun Question: Function Cloning

JavaScript Fun Question: Function Cloning

黄舟
黄舟Original
2017-01-22 14:57:201238browse

How to clone a function in JavaScript?

In other words, how to clone the parameter list and function body of a function into a new function?

For example, if there is such a Function.prototype.clone method, it 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

The new function is a completely new object. It has its own scope, but its usage is exactly the same as the original function.


First of all, you will definitely think of using eval. Eval can be said to be a devil with great magical powers.

Only a few lines of code are needed to achieve this requirement:

Function.prototype.clone = function(){  
    var func;  
    eval("func = " + this.toString());  
    return func;  
};

Since eval can work, then its brother Function can definitely do it too:

Function.prototype.clone = function(){  
    return new Function("return " + this.toString())();  
};

This line of code is even more incisive, but using Function in another way 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 writing method takes advantage of the characteristics of the Function function, first obtains the string of the original function, and intercepts The parameter list and the string of the function body are injected into the Function call in turn.


This interception process can be written using regular expressions to make the code more concise.

The above is the content of interesting JavaScript questions: function cloning. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn