如何从静态方法 ES6 类返回非静态变量



我有以下代码:

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-y 的编写方式,并且类本身不会添加任何内容。

构造函数适用于实例

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

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

如果出于某种原因,无论如何您都必须在constructor中设置它,则正确的语法将是 Utils.dateFormat = "..." .有趣的一面事实是,您可以在阅读时使用this(在return语句中(。但是,您仍然必须实例化Utils实例才能使dateFormat成为sth。除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());
    }
}

最新更新