Unique Function Identification in JavaScript

Is there any way to uniquely identify a function without providing it with the expando property? I just used "toString ()" to identify the function, but when the two functions are identical, they conflict.

The following code example reproduces the problem. In my actual code, the key for the "myfunctions" associative array is also built from other parameters. I don’t want to generate a meaningless key, since developers using this code should be able to rebuild this key at any time without reference to some random key.

var myfunctions = {}; (function(){ var num = 1; function somefunc() { alert(num); } myfunctions[somefunc.toString()] = somefunc; })(); (function(){ var num = 2; function somefunc() { alert(num); } myfunctions[somefunc.toString()] = somefunc; })(); for (var f in myfunctions) { myfunctions[f](); } 

When this code is run, only one warning is triggered, and it always has a β€œ2” message.

+4
source share
2 answers

Answer: no, there is no unique string value that you can draw from a function with which you can associate this particular instance.

Why do you want to avoid using expando?

+2
source

I suspect that everything you specified in the property name (not a hash key, property name) will in any case be converted to a string.

This does not work.

 (function(){ var num = 1; function somefunc() { alert(num); } somefunc.blah = 1; myfunctions[somefunc] = somefunc; })(); (function(){ var num = 2; function somefunc() { alert(num); } somefunc.bloh = 1; myfunctions[somefunc] = somefunc; })(); 

I just did the reading , and it seems that the property name can only be a string.

0
source

All Articles