如何从静态方法 ES6 return 非静态变量 Class

How to return non static variable from static method ES6 Class

我有以下代码:

export class Utils{
    constructor() {
        this.dateFormat = "MM-DD-YY";
    }

    static getFormat() {
        return this.dateFormat;
    }
}

当我尝试将此 class 导入其他文件并尝试调用静态方法 gteFormat 时 return undefined。 这是我的做法:

import * as Utils from "./commons/Utils.js";

class ABC {
    init(){
        console.log(Utils.Utils.getFormat());// gives undefined
    }
}

如何使这个静态方法 return 成为 dateFormat 属性?

构造函数用于实例

想一想:创建实例时会调用 constructor,设置静态默认值可能最好在其他地方完成,例如在声明静态变量时

class Utils {

    static dateFormat = "MM-DD-YY";
    
    static getFormat() {
        return this.dateFormat;
    }
}

console.log(Utils.getFormat())

如果出于某种原因您必须在 constructor 中设置它,则正确的语法将是 Utils.dateFormat = "..."。有趣的是,您可以在阅读时使用 this(在 return 语句中)。但是,您仍然必须实例化 Utils 的实例才能使 dateFormat 成为某事。除了 undefined:

class Utils {

    static dateFormat;
    
    constructor() {
       Utils.dateFormat = "MM-DD-YY"; // use Utils.dateFormat when writing
    }
    
    static getFormat() {
        return this.dateFormat; // use whatever you like when reading... :/
    }
}

console.log(`Before instanciating: ${Utils.getFormat()}`);

var dummy = new Utils();

console.log(`After instanciating: ${Utils.getFormat()}`);

关于您的 import 陈述的旁注

您可以避免每次都调用 Utils.Utils.getFormat(),这看起来有点奇怪,方法是像这样重构您的 import-语句:

// import * as Utils from "./commons/Utils.js";
import { Utils } from "./commons/Utils.js";

class ABC {
    init(){
        //console.log(Utils.Utils.getFormat());
        console.log(Utils.getFormat());
    }
}

如果您在概念上使用一堆函数,您可以考虑依赖模块范围本身来保护隐私,而不是 class 结构。然后您可以直接导出函数或值。喜欢

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

用一堆静态方法导出 class 是一种非常 Java-y 的写法,class 本身什么也没有添加。