我有以下代码:
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
属性?
最佳答案
如果您在概念上使用一堆函数,则可以考虑依靠模块范围本身来保护隐私,而不是类结构。然后您可以直接导出函数或值。喜欢
const dateFormat = "MM-DD-YY";
export function getFormat() {
return dateFormat;
}
用法如下
import * as Utils from "./commons/Utils.js";
console.log(Utils.getFormat())
甚至
import { getFormat } from "./commons/Utils.js";
console.log(getFormat())
或者如果它实际上是一个常量,您可以直接导出它
export const DATE_FORMAT = "MM-DD-YY";
然后
import { DATE_FORMAT } from "./commons/Utils.js";
console.log(DATE_FORMAT);
导出带有一堆静态方法的类是一种非常 Java 风格的编写方式,并且类本身不会添加任何内容。
关于javascript - 如何从 ES6 类的静态方法返回非静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42198214/