Claire
Claire

Reputation: 3184

Can a JavaScript function rename itself?

I realize a function can be copied to a new variable very easily by writing:

var wu = function() {
   // do stuff
)

var tang = wu;
var bee = tang;
// etc

and in this way can go by a theoretically infinite number of names. I also realize that in the above example, I could then say var wu = undefined and the reference would be removed, but I’m wondering if a function can rename itself as part of its own context? Meaning, can I write:

function wuTang() {
   // do stuff
   // rename self
}

wuTang(); // runs successfully
wuTang(); // returns undefined 

I’m not worried about the process of creating a new name, I’m simply wondering if this is possible. I do not want to call a second function to rename the original function, I want the function to rename itself so it can only be invoked by a given name one time.

Upvotes: 2

Views: 148

Answers (2)

François Huppé
François Huppé

Reputation: 2116

Yes, it is possible. To rename a function, you need to add a new name to it, and then remove its old name. Example:

 function wuTang() {
        newWuTang = wuTang; // Add new name (reference) to the function
        wuTang = undefined; // Remove old name (reference)
 }

In this case, note the absence of keyword (var,let,const,...) in front of newWuTang is what you want, because according to w3:

If you declare a variable, without using "var", the variable always becomes GLOBAL.

This function will run one time only as wuTang, and will rename itself as newWuTang.

I once used something similar with some eval in my function so I could pass the new wanted name as an argument to the function. But you know what they say about eval... I must have felt pretty wild that day!

Upvotes: 2

Strelok
Strelok

Reputation: 51441

window.wutang = function() {
  var f = window.wutang;
  window.watang = f;
  delete window.wutang;
}

That should be sufficient to “rename” itself :)

wutang(); // ok
wutang(); // fail
watang(); // should kill self :)

Upvotes: 3

Related Questions