JavaScript Reflection:获取变量的名称?
我有几个变量被分配给同一个函数。属性“name”是“”,因为该函数是匿名的;
也不涉及函数调用,因此没有被调用者。
JS中有没有办法通过自己实现的反射算法来获取变量的名称?
例如
var x = function(){}
var myUnknownNamedVar1 = myUnknownNamedVar2 = x;
背景:
为了空间效率,数千个变量名称被分配给与延迟加载树桩相同的“静态”函数,这些变量名称在第一个时被解析为单独的函数调用调用。 (变量名还包含命名空间)。
替代方案:
我的替代方案是使用诸如 {_name: myUnknownNamedVar1 , _fn: x}
之类的对象
。此问题的解决方案会很有趣。一个特殊的问题是辨别脚本中具有不同名称的变量,这些变量指向同一对象。
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.
Is there a way in JS to obtain the variable's name, through a self-implemented reflection algorithm?
e.g.
var x = function(){}
var myUnknownNamedVar1 = myUnknownNamedVar2 = x;
Background:
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).
Alternatives:
My alternative would be the use of objects such as {_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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可以使用对象反射,如下所示:
It is possible to use object reflection, as such:
不,没有。
对此的一个简单解释(强化了帖子中的观点)很简单:变量(或属性)不是值/对象。相反,它是值/对象的“名称”。同一个对象可以被命名多次。
想象一下这个例子,并考虑它如何映射到给人们的“名字”:-)
快乐编码。
No. There is not.
A simple explanation (that reinforces the point in the post) for this is simply: a variable (or property) is not a value/object. Rather, it is a "name" for a value/object. The same object can be named multiple times.
Imagine this example, and consider how it maps to "names" given to people :-)
Happy coding.
1. 您可以尝试解析脚本的文本。
JSFiddle 示例
2. 您可以尝试比较值
JSFiddle 示例
注意: 两种方法都需要改进(例如递归,更好/更多的匹配模式)。第二个仅查看全局变量,而闭包中的某些变量可能不会暴露给全局命名空间。此外,还有对象的对象。
1. You could try parsing the script's text.
JSFiddle Example
2. You can try comparing values
JSFiddle Example
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.
您可以使用装饰器来检测变量的名称,该变量必须是:
(a)- 类
(b)- 类或实例的属性
(c)- 类或实例的方法
装饰器提供有关装饰的 3 个信息:
因此:
target.name
(b)或(c)的名称直接是
key
示例(尝试小提琴) :
尝试 Fiddle
You can use decorators to detect the name of variable that must be :
(a)- Class
(b)- Attribute of class or of instance
(c)- Method of class or of instance
The decorator provides 3 informations about the decorated :
Thus:
target.name
the name of (b) or (c) is
key
directlyexample (Try Fiddle) :
Try Fiddle
你可以做的一个技巧是这样的:
One trick you can do is something like this: