简体   繁体   English

我应该/是否必须导出 Javascript ES6 中另一个导出的 class 返回的 class?

[英]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?在任何情况下我也应该导出Foo吗? Why/Why not?为什么/为什么不?

Should I export Foo too in any situation?在任何情况下我也应该导出 Foo 吗? 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 .如果您希望您的客户能够创建Foo对象的唯一方法是调用bar.generateFoo() ,那么没有理由导出Foo In Javascript, you can fully reference all Foo methods on an already constructed object without exporting the class itself.在 Javascript 中,您可以完全引用已构建的 object 上的所有Foo方法,而无需导出 class 本身。

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.另一方面,如果您希望模块的某些客户端能够使用new Foo(someValue)直接实例化Foo object ,那么您需要导出Foo以使其成为可能。

Exporting a class is exporting the constructor function.导出 class 就是导出构造函数 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() ).因此,如果您希望某人能够直接调用构造函数(例如,使用new Foo()构造一个新的 object ),则需要执行该导出。 If they don't need to call the constructor directly, then you don't need to export it.如果他们不需要直接调用构造函数,那么你不需要导出它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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