【发布时间】: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