创建新类与使用 export const 的区别 [英] Differences between creating a new class to using export const

查看:15
本文介绍了创建新类与使用 export const 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置:

  • BabelJS(es2015,react,stage-1)
  • 网络包
  • 反应/还原

CommonJS 和 ES6 的新手.我知道对象实例和静态方法容器之间的区别,但我不确定它们在分离到模块时的行为方式.所以我想知道返回实例之间有什么区别(这种模式是否有效?):

New to CommonJS and ES6. I know the difference between an object instance and a static container of methods but I am not sure how they behave when separated to modules. So I wonder what are the differences between returning an instance (is this pattern valid at all?):

// StateParser.js

class StateParser {
    constructor() {
     }

     method1() {
        ...
     }

}

export default new StateParser()

并导出 const 方法:

and exporting const methods:

// StateParser.js

let state = {
}

export const method1 = () => { ... }

  1. 方法A:每次导入都会有一个新实例吗?
  2. 方法 B:是使用对象解构的能力的好处之一:

  1. Method A: Would there be a new instance every time I import?
  2. Method B: Is one of the benefits the ability to use object destructuring:

import { method1 } from '../utils/StateParser.js';

然后使用method1就好像它存在于本地一样?

and then use method1 as if it existed locally?

方法 A:在构造函数中初始化状态的能力是好处之一吗?

Method A: Is one of the benefits the ability to initialize state in the constructor?

所以基本上我不确定何时为我的实用程序类使用哪个,并感谢您的输入.

So basically I am not sure when to use which for my utility classes and would appreciate your input.

推荐答案

每次导入A都会有新的实例吗?

Would there be a new instance every time I import A?

不,模块只评估一次.

B 的好处之一是能够使用对象解构然后使用 method1 就好像它存在于本地一样吗?

Is one of the benefits of B the ability to use object destructuring and then use method1 as if it existed locally?

是的,虽然它不称为解构".它们是命名导入(或模块的命名导出),并且它们不嵌套并使用不同的别名语法.

Yes, though it's not called "destructuring". They're named imports (or named exports of the module), and they don't nest and use a different syntax for aliasing.

A 的好处之一是能够在构造函数中初始化状态吗?

Is one of the benefits of A the ability to initialize state in the constructor?

没有.您也可以直接在模块范围内初始化模块状态,您不需要构造函数.

No. You can initialise module state just directly in the module scope as well, you don't need a constructor function for that.

但是,如果您在实例中有状态,最好使用一个可以实例化多次的类.为此,您当然需要导出类本身,而不是实例.

But yes, if you have state in the instances, it's a good idea to use a class which you can instantiate multiple times. For that, you need to export the class itself, not an instance, of course.

export default new ... 模式是否有效?

不,由于上述原因,这是一种反模式.鉴于该类在其他任何地方都没有使用,它与 匿名类 反模式非常相似.并且导出多个命名导出无论如何比默认导出对象要好得多.

No, it's an antipattern for the reasons outlined above. Given the class is used nowhere else, it's quite similar to the anonymous class antipattern. And exporting multiple named exports is much better than default-exporting objects anyway.

这篇关于创建新类与使用 export const 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆