简体   繁体   中英

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() .

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() .

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?

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. 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.

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.

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:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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