使用导出常量创建新类之间的差异 [英] Differences between creating a new class to using export const

查看:125
本文介绍了使用导出常量创建新类之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置:


  • BabelJS(es2015,react,stage-1)

  • Webpack

  • React / redux

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?

否,模块只能评估一次。

No, modules are only evaluated once.


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

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

是的,虽然没有被称为破坏。它们是命名为import (或命名为export 的模块),并且它们不嵌套并使用不同的语法进行别名。

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.


导出默认值新的... 模式有效?

不,这是一个反模式,原因如上。鉴于该类别不在其他地方,这与匿名类别反模式非常相似。并且导出多个命名导出比默认导出对象好多了。

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.

这篇关于使用导出常量创建新类之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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