What is the difference between export and public in typescript?

 ̄綄美尐妖づ 提交于 2019-12-04 19:11:31

问题


I think this is a different slant on this question. And maybe the question is better phrased, when would you use public, as opposed to export? From my reading it seems like anywhere a C#/Java person thinks public, what you actually want is export.

When/where would you use public instead of export?


回答1:


public as a visibility modifier technically does nothing (all class members are public by default); it exists as an explicit counterpart to private. It's legal only inside classes.

export does two different things depending on its context (on a top-level member in a file or in a module block).

At the top level of a file, export means that the containing file is an external module (i.e. it will be loaded using RequireJS, Node's require command, or some other CommonJS/AMD-compliant loader) and that the symbol you put export on should be an exported member of that external module.

Inside a module block, export means that the specified member is visible outside that module block. The default for things in module blocks is "closure privacy" -- unexported objects are not visible outside the module. When a declaration inside a module has the export modifier, it instead becomes a property of the module object that can be accessed from outside the module.

There is no place in the language where both public and export are legal, so choosing is relatively easy in that regard.




回答2:


export is specifically for modules e.g.:

module foo{
    export var bar;
}

public is for class members / methods e.g.:

class Foo{
    public bar = 123;
}

If you want to learn more about modules I did a video on that : http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1



来源:https://stackoverflow.com/questions/20060987/what-is-the-difference-between-export-and-public-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!