簡體   English   中英

Javascript ES6:如何從超類中定義的靜態方法中檢索調用子類

[英]Javascript ES6: How to retrieve calling subclass from a static method defined in superclass

JavaScript 新手。

尋求有關如何使用 ES6 類從超類中定義的靜態方法訪問調用類名稱的一些指導。 我花了一個小時搜索,但一直沒能想出一個解決方案。

代碼片段可能有助於澄清我正在尋找的內容

class SuperClass {
    get callingInstanceType() { return this.constructor.name }
    static get callingClassType() { return '....help here ...' }
}

class SubClass extends SuperClass { }

let sc = new SubClass()

console.log(sc.callingInstanceType)     // correctly prints 'SubClass'
console.log(SubClass.callingClassType)  // hoping to print 'SubClass'

如上所示,我可以輕松地從實例中獲取子類名稱。 不太確定如何從靜態方法訪問。

歡迎實現static get callingClassType()想法。

callingClassType是一個函數(好吧,在這種情況下是一個 getter,同樣的事情)。 函數內this的值取決於它的調用方式。 如果您使用foo.bar()調用函數,則this內部bar將引用foo

因此,如果您使用SubClass.callingClassType “調用”該函數,則this將引用SubClass SubClass本身是一個(構造函數)函數,因此您可以通過name屬性獲取它的name

所以你的方法定義應該是

static get callingClassType() { return this.name; }

 class SuperClass { get callingInstanceType() { return this.constructor.name } static get callingClassType() { return this.name } } class SubClass extends SuperClass {} let sc = new SubClass() console.log(sc.callingInstanceType) console.log(SubClass.callingClassType)

看一看在MDN文檔,以了解更多關於this

使用SuperClass.prototype.constructor.name

 class SuperClass { get callingInstanceType() { return this.constructor.name } static get callingClassType() { return SuperClass.prototype.constructor.name; } } class SubClass extends SuperClass {} class SubClass2 extends SuperClass { static get callingClassType() { return SubClass2.prototype.constructor.name; } } console.log(SuperClass.callingClassType); // 'SuperClass' console.log(SubClass.callingClassType); // 'SuperClass' console.log(SubClass2.callingClassType); // 'SubClass2'

來自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static#Examples

class Triple {
  static triple(n) {
    if (n === undefined) {
      n = 1;
    }
    return n * 3;
  }
}

class BiggerTriple extends Triple {
  static triple(n) {
    return super.triple(n) * super.triple(n);
  }
}

console.log(Triple.triple());        // 3
console.log(Triple.triple(6));       // 18

var tp = new Triple();

console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)

console.log(tp.triple());
// 'tp.triple is not a function'.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM