简体   繁体   中英

Should/do I have to export returning class returned by another exported class in Javascript ES6?

Consider the following module:

export class Bar {

    generateFoo() {
        return new Foo(1);
    }

}

class Foo {

    constructor(fooValue) {
        this.fooValue = fooValue;
    }

    doFoo() { console.log(this.fooValue); }

}

Should I export Foo too in any situation? Why/Why not?

Should I export Foo too in any situation? Why/Why not?

The only reason to export something from a module is if you want code from outside to be able to call it or reference it directly. If the only way you want your clients to be able to create Foo objects is by calling bar.generateFoo() , then there is no reason to export Foo . In Javascript, you can fully reference all Foo methods on an already constructed object without exporting the class itself.

If, on the other hand, you want some client of your module to be able to directly instantiate a Foo object with new Foo(someValue) , then you would need to export Foo to make that possible.

Exporting a class is exporting the constructor function. So, you need to do that export if you want someone to be able to call the constructor directly (eg construct a new object with new Foo() ). If they don't need to call the constructor directly, then you don't need to export it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM