JavaScript:克隆一个功能 [英] JavaScript: clone a function

查看:86
本文介绍了JavaScript:克隆一个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



想到两个选项: eval (func.toString()) function(){return func.apply(..)} 。但我担心eval的性能,并且包装会使堆叠变得更糟,并且如果应用了很多或应用于已包装,性能可能会降低性能。

新函数(args,body)看起来不错,但是我可以如何可靠地将现有的函数拆分为args和body,而无需JS中的JS解析器?



在此先感谢。



更新:
我的意思是能够做到

  var funcB = funcA.clone(); // clone()是我的扩展
funcB.newField = {...}; //不影响funcA


解决方案

试试这个:

  var x = function(){
return 1;
};

var t = function(a,b,c){
return a + b + c;
};


Function.prototype.clone = function(){
var that = this;
var temp = function temporary(){return that.apply(this,arguments); };
for(var key in this){
if(this.hasOwnProperty(key)){
temp [key] = this [key];
}
}
return temp;
};

alert(x === x.clone());
alert(x()=== x.clone()());

alert(t === t.clone());
alert(t(1,1,1)=== t.clone()(1,1,1));
alert(t.clone()(1,1,1));


What is a fastest way to clone a function in JavaScript (with or without its properties)?

Two options coming to mind are eval(func.toString()) and function() { return func.apply(..) }. But I am worried about performance of eval and wrapping will make stack worse and will probably degrade performance if applied a lot or applied to already wrapped.

new Function(args, body) looks nice, but how exactly can I reliable split existing function to args and body without a JS parser in JS?

Thanks in advance.

Update: What I mean is being able to do

var funcB = funcA.clone(); // where clone() is my extension
funcB.newField = {...};    // without affecting funcA

解决方案

try this:

var x = function() {
    return 1;
};

var t = function(a,b,c) {
    return a+b+c;
};


Function.prototype.clone = function() {
    var that = this;
    var temp = function temporary() { return that.apply(this, arguments); };
    for(var key in this) {
        if (this.hasOwnProperty(key)) {
            temp[key] = this[key];
        }
    }
    return temp;
};

alert(x === x.clone());
alert(x() === x.clone()());

alert(t === t.clone());
alert(t(1,1,1) === t.clone()(1,1,1));
alert(t.clone()(1,1,1));

这篇关于JavaScript:克隆一个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆