You’ll probably never need to do this (and given the solution, you’ll have an extra reason for not doing it), but just in case you need it that one time, here it is. So, for whatever reason, you need a copy of a JavaScript function – not a reference to the original function, but a separate function which does the exactly the same thing as the original function. Here’s how you can do this:
function one(){ alert("one"); } eval("var two = " + one.toString()); // CREATE THE COPY* delete(one); // this will illustrate that “two” is indeed a separate copy two(); // alerts "one"
When might you want to use this?
Lets say that you have a function which is used all over a large site. But in one, new instance you want it to do what it normally does, plus something else. And, since calls to the original function are scattered across many files across the site, you can’t update the calls to the function themselves. In fact, you may not even have access to the calls. You’re left with a couple of options:
- Locally re-define the original function to contain all of the code of the original function, plus the new stuff. The problem here is that you now have 2 copies of the same code and, should the original function require changes, you’ll need to make those changes in 2 places. (Obviously, if you do make more local copies, you’ll need to update each version making this more than double bad.)
- Make a new function by dynamically duplicating the original function, then re-define the original function to call the duplicate, plus the extra stuff. Then, the original code still exists only once and you don’t have to worry about maintaining multiple versions. You do this by eval-ing a new string which contains the variable definition with the contents of the original function converted to a string using the built-in toString() method.
* eval() is evil.