如何检查变量是否是ES6类声明? [英] How to check if a variable is an ES6 class declaration?
本文介绍了如何检查变量是否是ES6类声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从一个模块导出以下ES6类:
导出类Thingy {
hello
console.log(A);
}
world(){
console.log(B);
}
}
并从另一个模块导入:
importThingyfromthingy;
if(isClass(Thingy)){
// Do something ...
}
如何检查变量是否是类?不是类实例,而是类声明?
换句话说,
在上面的例子中,c $ c> isClass 类,当代码运行时,你只有一个构造函数,或一个对象。所以你可以做
if(typeof Thingy ==='function'){
//这是一个函数,所以它绝对不能是一个实例。
} else {
//它可以是除了构造函数之外的任何东西
}
只要你知道事物是一个实例或一个构造函数。
I am exporting the following ES6 class from one module:
export class Thingy {
hello() {
console.log("A");
}
world() {
console.log("B");
}
}
And importing it from another module:
import {Thingy} from "thingy";
if (isClass(Thingy)) {
// Do something...
}
How can I check whether a variable is a class? Not a class instance, but a class declaration?
In other words, how would I implement the isClass
function in the example above?
解决方案
In ES6, there is no "class" when code is running, you just have a constructor function, or an object. So you could do
if (typeof Thingy === 'function'){
// It's a function, so it definitely can't be an instance.
} else {
// It could be anything other than a constructor
}
As long as you know for a fact that something is either an instance or a constructor.
这篇关于如何检查变量是否是ES6类声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文