问题描述
我希望能够将任何引用(函数,对象或
数组)转换为唯一的字符串ID,然后检索原始引用
使用相同的ID。
以下代码执行此操作但仅适用于函数,对于某些
未知原因不适用于其他类型引用。
var func = function(){};
var ref_id = $ GS(func);
//得到原始参考
var func_2 = $ GO(ref_id);
函数$ GS(ref){return jsref(ref," gstr"); }
函数$ GO(s){return jsref(s," gobj"); }
函数jsref(ref,what){
//猜测
if(!what){
what =(typeof(ref)==" string")? " gobj" :" gstr";
}
var c = jsref;
if(!c.str_ref )c.str_ref = {};
if(!c.ref_str)c.ref_str = {};
if(!cn)cn = 0;
if(what ==" gstr"){
if(!c.ref_str [ref]){
c.n ++ ;
c.ref_str [ref] = cn;
c.str_ref [cn] = ref;
}
return" jsref:" + c.ref_str [ref];
}
else if(what ==" gobj"){
ref = ref.replace(/ \ D + / g,'''');
返回c.str_ref [ref];
}
返回null;
}
I would like to be able to convert any reference (function, object, or
array) into unique string id and retrieve original reference afterwards
using same id.
The following code does this but only for functions, and for some
unknown reason does not work properly for other kind of references.
var func = function(){};
var ref_id = $GS(func);
// get original reference
var func_2 = $GO(ref_id);
function $GS (ref) { return jsref(ref, "gstr"); }
function $GO (s) { return jsref(s, "gobj"); }
function jsref (ref, what) {
// guess
if (!what) {
what = (typeof(ref) == "string") ? "gobj" : "gstr";
}
var c = jsref;
if (!c.str_ref) c.str_ref = {};
if (!c.ref_str) c.ref_str = {};
if (!c.n) c.n = 0;
if (what == "gstr") {
if (!c.ref_str[ref]) {
c.n++;
c.ref_str[ref] = c.n;
c.str_ref[c.n] = ref;
}
return "jsref:"+ c.ref_str[ref];
}
else if (what == "gobj") {
ref = ref.replace(/\D+/g, '''');
return c.str_ref[ref];
}
return null;
}
推荐答案
这篇关于唯一引用ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!