Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  92] [ 1]  / answers: 1 / hits: 133651  / 15 Years ago, wed, december 2, 2009, 12:00:00

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?


Update:
What I mean is being able to do


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

More From » function

 Answers
25

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

[#98171] Sunday, November 29, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zoiel

Total Points: 692
Total Questions: 90
Total Answers: 89

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
zoiel questions
Mon, Jun 10, 19, 00:00, 5 Years ago
Thu, Mar 21, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;