tags:

views:

73

answers:

2

Is there any way I can uniquely identify a function without giving it an expando property? I've been just using "toString()" to identify the function, but when two functions are identical, they conflict.

The following sample code reproduces the problem. In my actual code, the key for the associative array "myfunctions" is built from other parameters as well. I don't want to generate a meaningless key since the developers using this code need to be able to rebuild this key at any time without holding a 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 alert fires, and it always has the message "2".

+1  A: 

The answer is no, there isn't any unique string value you can draw from a function with which you can associate that specific instance.

Why do you want to avoid using an expando?

AnthonyWJones
This is all part of an eventing model which is part of a larger API being sold to 3rd party developers. I do not want to modify their functions even if it's just adding a property to identify the function. However, if that is my only recourse, then I'll have to use an expando.Thanks for *reading* and answering my question!
Freyday
A: 

I suspect that whatever you put in a property name (not a hash key, a property name) will be converted to string anyway.

This does not work either

(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 some reading, and it seems like a property name can only be a string.

Victor
use the expando as the key.myfunctions[somefunc.blah] = somefunc;
Freyday