简体   繁体   English

如何在javascript中检查目标是否为“类”

[英]How to check target is “class” or not in javascript

Since ECMAScript 2015, jvascript start to support class declaration. 从ECMAScript 2015开始,jvascript开始支持类声明。 But there is no way to distinguish between 'class declaration' and 'function declaration'. 但是无法区分“类声明”和“功能声明”。

class yesClass {
  //It is possible to omit defining constructor
  constructor () {}
}
typeof yesClss; //"function"
yesClss instanceof Function; //true
yesClss instanceof Object; //true
yesClass.constructor.name; //"Function"

There is no way to distinguish them? 有没有办法区分它们?

In javascript, class declaration requires 'new' operator to use a constructor, which exist or not. 在javascript中,类声明要求“ new”运算符使用存在或不存在的构造函数。 So call class without 'new' operator occurs TypeError. 因此,没有“ new”运算符的调用类会发生TypeError。

class yesClass {}
yesClass();
//Uncaught TypeError: Class constructor yesClass cannot be invoked without 'new'

This "TypeError" can be caught with "try ... catch ...", like following: 可以使用“ try ... catch ...”来捕获此“ TypeError”,如下所示:

try {
  yesClass();
} catch ( e ) {
  //Case of user-defined class, "Class constructor ..."
  //Case of native function which behaves like class, Document, "Failed to construct ..."
  console.log( e.message.match( /^Class constructor/ ) !== null || e.message.match( /^Failed to construct/ ) !== null );
}

Heading code let you know that is "class declaration" or not. 标题代码让您知道是否是“类声明”。

The other simple and limited way, specified in a REAL class declaration, is using toString method. 在REAL类声明中指定的另一种简单且受限制的方式是使用toString方法。 When the target is user-defined class, the result of toString method starts with "class". 当目标是用户定义的类时,toString方法的结果以“ class”开头。

yesClass.toString();
//"class yesClass {}"

The Object has the top hierarchy in javascript and toString method is a method of Object. Object在javascript中具有最高的层次结构,并且toString方法是Object的方法。 Therefore every object in javascript has toString method except several cases which are some native objects and manually removed objects. 因此,javascript中的每个对象都具有toString方法,除了几种情况外,它们是一些本机对象和手动删除的对象。

Test following "JS Bin" archive to test heading context. 测试以下“ JS Bin”归档文件以测试标题上下文。 In the following link, I wrote a function, which named as "isClass". 在下面的链接中,我编写了一个名为“ isClass”的函数。 This function returns boolean or object, differs by parameters. 此函数返回布尔值或对象,因参数而异。 https://jsbin.com/tekeyu/edit?js,console https://jsbin.com/tekeyu/edit?js,控制台

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

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