使用默认值时调用静态方法

编程入门 行业动态 更新时间:2024-10-13 12:16:37
本文介绍了使用默认值时调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用ES6模块和导出默认类时,如何从同一类中的另一个方法调用静态方法?我的问题专门针对何时将类标记为默认类(与 es6调用静态方法不同)

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)

以下示例说明了不使用默认值(即 Test.staticMethod()?)时如何从非静态方法调用静态方法?

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(); } }

推荐答案

您可以使用 this.constructor.…

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(); } }

如果您由于某些原因不能执行此操作 1 ,那么还会有此hack:

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:我无法想象一个好人

更多推荐

使用默认值时调用静态方法

本文发布于:2023-08-04 09:14:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1295016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时调   静态   默认值   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!