【问题标题】:How to return non static variable from static method ES6 Class如何从静态方法 ES6 类返回非静态变量
【发布时间】:2017-02-13 06:55:53
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • this 指的是类中的特定对象。静态方法不与任何对象关联,那么您希望this.dateFormat 返回什么?
  • 如果你想有一个默认的dateFormat,把它声明为类中的一个变量,而不是一个对象的属性。
  • @Barmar:谢谢,现在我能想到的就是:Utils.dateFormat='myformat'。这是正确的方法还是有更好的方法?
  • 如果你的类里只有静态方法,你根本不需要类,只需要导出函数。
  • @loganfsmyth:我有多个静态方法,它们可能会使用一些常见的常量。我不确定我将如何制作这些方法。我不想将这些常量放在其他文件中,因为它们只在这里需要。

标签: javascript class static ecmascript-6 export


【解决方案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的写法,而类本身什么也不加。

【讨论】:

  • 谢谢,我想我必须走这条路。我希望有其他方式可以使用类来保持一致。
  • 我真的建议不要这样想。 Javascript 是一种基于函数的语言,类是最重要的,而不是相反。对所有事物都使用类会使事情变得不必要地复杂。
【解决方案2】:

构造函数用于实例

想一想:在创建实例时调用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 声明的旁注

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

// 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());
    }
}

【讨论】:

  • 谢谢,但我想知道在调用构造函数时是否提供static 的目的。
  • 我不这么认为,我只是想指出可以这样做;)
  • 也看看@loganfsmyth 的回答,它指出了一些解决实际问题的好方法
猜你喜欢
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多