繁体   English   中英

JavaScript:如何检测ES6类具有自己的构造函数?

[英]JavaScript: How to detect ES6 class has its own constructor?

如何检测EcmaScript类是否具有自己的构造函数? 请参见下面的代码段。

 class Person { constructor(name, age) { // <- Own constructor this._name = name; this._age = age; } } class Manager extends Person { // This class does not have it's own constructor } 

似乎没有明确的方法可以执行此检查。

谢谢大家的时间和帮助。

它不是防弹的,但是您可以将构造函数转换为字符串,然后查看它是否包含单词constructor(或类似的词

 function hasOwnConstructor(instance) { var str = instance.constructor.toString(); return /class(.*?[^\\{])\\{([\\s\\n\\r\\t]+)?(constructor[\\s]+?\\()/.test(str); } class thing1 { method() { return this; } } class thing2 { constructor(argument) { return this; } } var ins1 = new thing1(); var ins2 = new thing2(); console.log( hasOwnConstructor(ins1) ); // false console.log( hasOwnConstructor(ins2) ); // true 

误报仍然可能,但是正则表达式使检查非常严格,因此不太合理。

检查构造函数。

class Example {

    constructor(prop1, prop2) {

    this.prop1 = prop1;
    this.prop2 = prop2;

      }
    }

您可以通过构造函数将参数传递给您的类,该函数建立在创建新实例时可以全局引用的属性。

此行会将int 1和“ test”作为值传递给prop1和prop2:

const exampleVar = new Example(1, "test");

并可能呈现如下内容:

<Example prop1=1 prop2="test" />

希望这可以帮助。 如果具有构造函数,则为构造函数,如果不具有构造函数,则为不构造函数。

暂无
暂无

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

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