【问题标题】:Get static class name from extended class JavaScript从扩展类 JavaScript 获取静态类名
【发布时间】:2020-07-04 15:56:41
【问题描述】:

实例化对象时,我可以通过this.constructor.name在对象中获取调用者的类。

举个例子:

class Foo {

    /**
     * Get called class
     * @returns {String}
     */
    getCaller() {
        return this.constructor.name;
    }

};

class Bar extends Foo {


};

var foo = new Foo();
console.log(foo.getCaller()); // Foo

var bar = new Bar();
console.log(bar.getCaller()); // Bar

现在我需要调用基本相同的函数,但从扩展器中的静态函数调用。

class Foo {

    /**
     * @static
     * Get called class
     * @returns {String}
     */
    static getCaller() {
        return this.constructor.name; // <- any ideas?
    }

}

class Bar extends Foo {


}

console.log(Foo.getCaller()); // function
console.log(Bar.getCaller()); // function

【问题讨论】:

  • 你知道 javascript 类是一团糟,对吧?
  • 是的,说实话,他们也很好。
  • 顺便说一句,静态方法不属于实例,所以 this 在其中没有意义
  • 我知道,问题是如何检索静态调用者。
  • 在调用静态函数的时候要写类名,为什么还要这个?

标签: javascript node.js static


【解决方案1】:

class Foo {

    /**
     * @static
     * Get called class
     * @returns {String}
     */
    static getCaller() {
        return this.name;
    }

}

class Bar extends Foo {


}

console.log(Foo.getCaller()); // Foo
console.log(Bar.getCaller()); // Bar

【讨论】:

  • 谢谢,这样更整洁!
猜你喜欢
  • 2010-10-05
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
相关资源
最近更新 更多