Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

reactjs - Differences between creating a new class to using export const

Setup:

  • BabelJS (es2015, react, stage-1)
  • Webpack
  • React / redux

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()

and exporting const methods:

// StateParser.js

let state = {
}

export const method1 = () => { ... }
  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';
    

    and then use method1 as if it existed locally?

  3. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

No, modules are only evaluated once.

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.

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.

Is the export default new … pattern valid at all?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...