2

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.

Claire
  • 3,146
  • 6
  • 22
  • 37
  • 2
    Sure, put `wuTang = undefined;` in the function body? – Bergi Jun 12 '18 at 11:11
  • "*so it can only be invoked by a given name one time*" - notice that whoever your caller is, he could always save a reference to the function before calling it. – Bergi Jun 12 '18 at 11:34
  • @Bergi Ok I can remove a variable's reference to a function, but I can't do that in my second example above – Claire Jun 12 '18 at 20:21
  • Yes you can. (Have you tried it?) `function wuTang() {}` just creates a variable `wuTang` that references a function. – Bergi Jun 12 '18 at 20:27

2 Answers2

3
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 :)
Strelok
  • 50,229
  • 9
  • 102
  • 115
2

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!

François Huppé
  • 2,006
  • 1
  • 6
  • 15