TypeScript:在运行时获取类名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22777181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:53:52  来源:igfitidea点击:

TypeScript: get to get Class name at runtime?

reflectiontypescript

提问by Zach

In C#, it's easy to get the class name at runtime using Reflection. Is it possible in TypeScript?

在 C# 中,使用反射很容易在运行时获取类名。在打字稿中可能吗?

回答by Rahul Tripathi

At runtime you are running JavaScript. So you can check this answerfor details.

在运行时,您正在运行 JavaScript。因此,您可以查看此答案以了解详细信息。

Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)

这是一个可以满足您需要的 hack - 请注意,它会修改对象的原型,这是人们不喜欢的(通常是有充分理由的)

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};

Now, all of your objects will have the function, getName(), that will return the name of the constructor as a string. I have tested this in FF3 and IE7, I can't speak for other implementations.

现在,您的所有对象都将具有函数 getName(),它将以字符串形式返回构造函数的名称。我已经在 FF3 和 IE7 中测试过这个,我不能说其他实现。