Skip to content

Instantly share code, notes, and snippets.

@STRd6
Created December 5, 2013 21:09
Show Gist options
  • Save STRd6/7813942 to your computer and use it in GitHub Desktop.
Save STRd6/7813942 to your computer and use it in GitHub Desktop.
Rename function in JS
var f, rename, renamedFunction;
rename = function(fn, name) {
return Function("fn", "return (function " + name + "(){\n return fn.apply(this, arguments)\n});")(fn);
};
f = function() {};
renamedFunction = rename(f, "a_new_name");
alert(renamedFunction.name);
@logrusorgru
Copy link

// step 1
function x(i) { if (i < 2) return x(i+1); else return i; }
// step 2
var renamed = rename(x, 'rx');
// step 3
function x() { return 7; }
// step 4
renamed(0); // => 7
// step 5
rx(0)  // => ReferenceError: rx is not defined

@NAnusha1525
Copy link

can you explain how to rename a tabs dynamically in javascript

@FreezePhoenix
Copy link

@NAnausha1525 what is a tabs? Besides, that would be irrelevant

@CalinZBaenen
Copy link

@FreezePhoenix I think they mean like the name of the tab (hopefully that assumption is right).
@NAnusha1525 Even though it's irrelevant, if you haven't figured it out yet, you just need to select the HTML page's <title> tag, whether that be through the ID of the element, or by selecting all elements with the tag-name title, then you want to change the innerText to the new title. - Hope that helps.

@jonathan-annett
Copy link

jonathan-annett commented Nov 13, 2022

or if you don't want to decompile/recompile the function, you can just name it in place - it's simply an object after all

 Object.defineProperty(myStupidlyNamedFunction, "name", {value: "iLikeThisNameBetter", enumerable: false});

@CalinZBaenen
Copy link

@jonathan-annett, I thought the name field was frozen/unwritable.
Does Object.defineProperty(...) take precedence over that?

@jonathan-annett
Copy link

All i know is I've used that method with success, and seen it used elsewhere. I haven't tried it in every browser, so mileage may vary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment