JavaScript:克隆一个函数 [英] JavaScript: clone a function

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

问题描述

在 JavaScript 中克隆一个函数的最快方法是什么(有或没有它的属性)?

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

想到的两个选项是 eval(func.toString())function() { return func.apply(..) }.但我担心 eval 和 wrapping 的性能会使堆栈变得更糟,如果大量应用或应用于已经包装的,可能会降低性能.

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) 看起来不错,但是在 JS 中没有 JS 解析器的情况下,我如何可靠地将现有函数拆分为 args 和 body?

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?

提前致谢.

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

var funcB = funcA.clone(); // where clone() is my extension
funcB.newField = {...};    // without affecting 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));

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

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