我有以下代码:
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的方法,而类本身则不添加任何内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句