【发布时间】:2017-02-13 06:55:53
【问题描述】:
我有以下代码:
export class Utils{
constructor() {
this.dateFormat = "MM-DD-YY";
}
static getFormat() {
return this.dateFormat;
}
}
当我尝试将此类导入其他文件并尝试调用静态方法gteFormat 时,它返回undefined。
这是我的做法:
import * as Utils from "./commons/Utils.js";
class ABC {
init(){
console.log(Utils.Utils.getFormat());// gives undefined
}
}
如何让这个静态方法返回dateFormat 属性?
【问题讨论】:
-
this指的是类中的特定对象。静态方法不与任何对象关联,那么您希望this.dateFormat返回什么? -
如果你想有一个默认的
dateFormat,把它声明为类中的一个变量,而不是一个对象的属性。 -
@Barmar:谢谢,现在我能想到的就是:
Utils.dateFormat='myformat'。这是正确的方法还是有更好的方法? -
如果你的类里只有静态方法,你根本不需要类,只需要导出函数。
-
@loganfsmyth:我有多个静态方法,它们可能会使用一些常见的常量。我不确定我将如何制作这些方法。我不想将这些常量放在其他文件中,因为它们只在这里需要。
标签: javascript class static ecmascript-6 export