JavaScript反思:获取变量的名称? [英] JavaScript Reflection: obtaining a variable's name?

查看:90
本文介绍了JavaScript反思:获取变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个分配给同一功能的变量.属性名称"为",因为此函数是匿名的;

I have a several variables which are assigned to the same function. The property 'name' is "" as this function is anonymous;

也不涉及函数调用,因此也没有被调用者.

There also isn't a function call involved, and as such no callee.

JS中是否有一种通过自我实现的反射算法来获取变量名称的方法?

Is there a way in JS to obtain the variable's name, through a self-implemented reflection algorithm?

例如

var x = function(){}
var myUnknownNamedVar1 = myUnknownNamedVar2 = x;

背景:

为了节省空间,成千上万的变量名称被分配给与延迟加载的树桩相同的静态"函数,它们在第一次调用时就分解为单个函数. (变量名还包含一个名称空间).

for space efficiency, thousands of variable names are assigned to the same 'static' function as a lazy-loaded stumps, which get resolved to individual functions upon the first call invocation. (The variable name also contains a namespace).

替代:

我的替代选择是使用{_name: myUnknownNamedVar1 , _fn: x}

该问题的解决方案将很有趣.一个特殊的问题是在脚本中辨别具有不同名称的变量,这些变量指向同一对象.

Solutions to this issue would be interesting. A particular issue is discerning variables with different names ,in the script, which point to the same object.

推荐答案

1.您可以尝试解析脚本的文本.

JSFiddle示例

var x = function(){}
var myUnknownNamedVar1 = myUnknownNamedVar2 = x;

var txt  = (document.currentScript && document.currentScript.textContent) ||
           (document.scripts       && document.scripts[1]
                                   && document.scripts[1].textContent);
var arr  = txt.match(/var\s*(.*)\s*=\s*x\b/);
arr[1]   = arr[1].replace(/\s+$/,"");
var vars = arr[1].split(/\s*=\s*/);

// vars: ["myUnknownNamedVar1", "myUnknownNamedVar2"]


2.您可以尝试比较值

JSFiddle示例

var x = function(){}
var myUnknownNamedVar1 = myUnknownNamedVar2 = x;

var vars = [];
for (var prop in window){
    if (window[prop] == x)
      vars.push(prop);
}

// vars: ["x", "myUnknownNamedVar1", "myUnknownNamedVar2"]


注意:这两种方法都需要改进(例如,递归,更好/更多的匹配模式).第二个仅查看全局变量,而闭包中的某些变量可能不会公开给全局命名空间.另外,还有一些对象.


Note: Both methods will need refining (eg recursion, better/more match patterns). The second one only looks at global variables, whereas some variables in closures may not be exposed to the global namespace. Also, there are objects of objects.

这篇关于JavaScript反思:获取变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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