Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniquely identify a function in JavaScript

Tags:

javascript

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".

like image 663
mikefrey Avatar asked Nov 06 '22 19:11

mikefrey


1 Answers

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?

like image 96
AnthonyWJones Avatar answered Nov 15 '22 06:11

AnthonyWJones