Reputation: 7449
When using ES6 modules and export default class
how is it possible to call a static method from another method within the same class? My question refers specifically to when the class is marked as default (unlike es6 call static methods)
The below example illustrates how it is possible to call the static method from a non-static method when not using default, i.e. Test.staticMethod()
?
export default class {
static staticMethod(){
alert('static');
}
nonStaticMethod(){
// will not work because staticMethod is static.
// Ordinarily you would use MyClass.staticMethod()
this.staticMethod();
}
}
Upvotes: 1
Views: 262
Reputation: 48230
You can name your exported class and refer to it by the auxiliary name:
export default class _ {
static staticMethod(){
alert('static');
}
nonStaticMethod(){
_.staticMethod();
}
}
Upvotes: 2
Reputation: 664297
You can use this.constructor.…
if you dare, but the better solution would be to just name your class:
export default class MyClass {
static staticMethod(){
alert('static');
}
nonStaticMethod() {
// Ordinarily you just use
MyClass.staticMethod();
}
}
If you cannot do this for some reason1, there's also this hack:
import MyClass from '.' // self-reference
export default class {
static staticMethod(){
alert('static');
}
nonStaticMethod() {
// Ordinarily you just use
MyClass.staticMethod();
}
}
1: I cannot imagine a good one
Upvotes: 4