确定给定名称的类是否存在 [英] Determine if class of given name exists
问题描述
这可能是一个愚蠢的问题,但是我四处搜寻却一无所获.
This may be a silly question but I've searched around and found nothing.
我有一个代码:
class A {}
let className = 'A';
我需要检查className
是否对应于现有的类.
I need to check if className
corresponds to an existing class.
这都不在全局范围内,并且正在node.js中运行,所以我不能使用window
This is all not in the global scope and is running in node.js so I can't use window
我知道以下方法会起作用:
I know that the following would work:
eval(`typeof ${className} === 'function'`);
但是我有点不愿意使用eval
(而且小人也抱怨它)
However I am a bit reluctant to use eval
(and also the linter complains about it)
此外,我还需要将类实例化为变量,再次可以使用eval进行操作,如下所示:
In addition I need to also instantiate the class as a variable which again I can do with eval like so:
let ctor = eval(className);
let object = new ctor();
但这又使用了eval.
But again this uses eval.
还有其他方法可以实现这些目标吗?
Is there any alternative way to achieve these?
推荐答案
使用Function
构造函数
function ac(){} //new class
var f = new Function( "return typeof ac == 'function'" ) //define function to verify
f(); //returns true if class exists in the current scope
使其更通用
function ac(){} //new class
var f = function( className ){
return new Function( "return typeof " + className + " == 'function'" )(); //define function to verify and invoke the same
}
f( "ac" ); //returns true if class exists in the current scope
这篇关于确定给定名称的类是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!