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

时间:2017-02-13 06:55:54

标签: javascript class static ecmascript-6 export

我有以下代码:

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属性?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

构造函数用于实例

考虑一下:在创建实例时调用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());
    }
}
相关问题