在JavaScript中唯一标识函数 [英] Uniquely identify a function in JavaScript

查看:139
本文介绍了在JavaScript中唯一标识函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以在不给它一个expando属性的情况下唯一地识别一个函数?我一直只是使用toString()来识别函数,但是当两个函数相同时,它们会发生冲突。

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.

以下示例代码重现了该问题。在我的实际代码中,关联数组myfunctions的关键字也是从其他参数构建的。我不想生成无意义的密钥,因为使用此代码的开发人员需要能够在不保留对某个随机密钥的引用的情况下随时重建此密钥。

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]();
}

运行此代码时,只会触发一个警报,并且它始终具有消息2。

When this code is run, only one alert fires, and it always has the message "2".

推荐答案

答案是否定的,没有任何唯一的字符串值可以从函数中绘制您可以将该特定实例关联起来。

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.

为什么要避免使用expando?

Why do you want to avoid using an expando?

这篇关于在JavaScript中唯一标识函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆