簡體   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