简体   繁体   English

Typescript获取函数内设置变量的名称

[英]Typescript get name of setted variable inside a function

is it possible to get name of setted variable inside a function? 是否可以在函数内获取设置变量的名称?

public MyFunction(): any {
   //get myVarName as string;
}

var myVarName = MyFunction();

No, you cannot obtain the name of the myVarName variable inside of MyFunction() . 不,您无法在MyFunction()内获取myVarName变量的名称。

Inside of MyFunction() , there is no knowledge of what other variables might also contain a reference to MyFunction() or variables that might contain the results of calling MyFunction() . MyFunction()内部,不知道还有哪些其他变量也可能包含对MyFunction()的引用或可能包含调用MyFunction()的结果的变量。

Do you realize that this line of code: 您是否意识到这一行代码:

var myVarName = MyFunction();

actually calls MyFunction() and executes it, but myVarName isn't assigned until after the function runs? 实际调用MyFunction()并执行它,但是在函数运行之后才分配myVarName吗?

There could be zero, one or hundreds of other variable that contain a reference to the called function. 可能有零个,一个或数百个其他变量包含对被调用函数的引用。 There's just no linkage between a function and the variables that might also contain a reference to the function. 在函数和可能包含该函数引用的变量之间没有链接。 If you wanted such a linkage, you would have to somehow build your own data structure to keep track of that linkage and then MyFunction() could traverse that data structure to see who had a reference to it. 如果您需要这样的链接,则必须以某种方式构建自己的数据结构来跟踪该链接,然后MyFunction()可以遍历该数据结构以查看谁对其进行了引用。 But, every time you assigned a reference, you'd also have to modify this data structure that keeps track of that. 但是,每次分配参考时,您还必须修改此数据结构以跟踪该参考。

If, instead of a global variable like myVarName , all function references like this were kept in a known array or a known object, then it would be possible for MyFunction() to search that known array or object and find all entries that pointed to itself. 如果不是像myVarName这样的全局变量,而是将所有这样的函数引用都保存在已知数组或已知对象中,则MyFunction()可以搜索该已知数组或对象并找到指向自身的所有条目。 。

As always on StackOverflow, if you describe the problem you're really trying to solve (rather than the specific solution you're looking for) you will probably get better advice. 与在StackOverflow上一如既往,如果您描述的是您真正要解决的问题(而不是您要寻找的特定解决方案),则可能会得到更好的建议。

No. Since the variable assignment takes place after the function call. 不会。因为变量分配发生函数调用之后。

For anything that takes place up the stack calls you could have done a stacktrace: 对于发生在堆栈调用中的任何事情,您都可以执行stacktrace:

try{
   throw new Error('Buck stops here')
}catch(e){
   console.log(e.stack) // Yea!
}

More: http://tobyho.com/2011/06/08/the-javascript-stacktrace-blog/ 更多: http : //tobyho.com/2011/06/08/the-javascript-stacktrace-blog/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM