JavaScript:克隆一个函数?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (122)

在JavaScript中克隆函数的最快方法是什么?

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));
用户回答回答于

答案

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

绑定函数对象,将newFunc/oldFunc视为相同的实例。

(new newFunc()) instanceof oldFunc; //gives true
(new oldFunc()) instanceof newFunc; //gives true as well
newFunc == oldFunc;                 //gives false however

扫码关注云+社区

领取腾讯云代金券