简体   繁体   English

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

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

How to detect whether EcmaScript class has its own constructor? 如何检测EcmaScript类是否具有自己的构造函数? See code snippet below. 请参见下面的代码段。

 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 } 

It seems there is no clear way to do this check. 似乎没有明确的方法可以执行此检查。

Thank you all for time and help. 谢谢大家的时间和帮助。

It's not bulletproof, but you could convert the constructor to a string, and see if it contains the word constructor( or something similar 它不是防弹的,但是您可以将构造函数转换为字符串,然后查看它是否包含单词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 

False positives could still be possible, but the regex makes the check quite strict, so it's not very plausable. 误报仍然可能,但是正则表达式使检查非常严格,因此不太合理。

Inspect the constructor function. 检查构造函数。

class Example {

    constructor(prop1, prop2) {

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

      }
    }

You can pass parameters to your class via the constructor function that establishes properties which can be globally referenced when creating a new instance. 您可以通过构造函数将参数传递给您的类,该函数建立在创建新实例时可以全局引用的属性。

This line would pass int 1 and "test" as values to prop1 and prop2: 此行会将int 1和“ test”作为值传递给prop1和prop2:

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

and might render something like: 并可能呈现如下内容:

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

Hope this helps. 希望这可以帮助。 If it has a constructor function, there is a constructor, if it does not have the constructor function, then there is no constructor. 如果具有构造函数,则为构造函数,如果不具有构造函数,则为不构造函数。

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

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