JavaScript:克隆一个函数

新手上路,请多包涵

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

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

new Function(args, body) 看起来不错,但是在 JS 中没有 JS 解析器的情况下,我如何可靠地将现有函数拆分为 args 和 body?

提前致谢。

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

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

原文由 Andrey Shchekin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 503
2 个回答

尝试这个:

 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));

原文由 Jared 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个更新的答案

var newFunc = oldFunc.bind({}); //clones the function with '{}' acting as its new 'this' parameter

但是 .bind 是 JavaScript 的现代 ( >=iE9 ) 功能(具有 来自 MDN 的兼容性解决方法

笔记

  1. 不克隆 函数对象附加的附加 属性包括 原型 属性。 感谢@jchook

  2. 新函数 this 变量被 bind() 给出的参数卡住,即使在新函数 apply() 调用。 感谢@Kevin

 function oldFunc() {
  console.log(this.msg);
}
var newFunc = oldFunc.bind({ msg: "You shall not pass!" }); // this object is binded
newFunc.apply({ msg: "hello world" }); //logs "You shall not pass!" instead

  1. 绑定函数对象, instanceof 对待 newFunc / oldFunc 一样。 感谢@Christopher
 (new newFunc()) instanceof oldFunc; //gives true
(new oldFunc()) instanceof newFunc; //gives true as well
newFunc == oldFunc; //gives false however

原文由 PicoCreator 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题