15

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?

Community
  • 1
  • 1
David Thielen
  • 28,723
  • 34
  • 119
  • 193

2 Answers2

20

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.

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • Ok, so module and class I use export when I think public (from C#/Java). But for functions and variables in the class, are they also marked as export? Or are they by default public and no export is needed? – David Thielen Nov 19 '13 at 15:21
  • There is no concept of "export" inside a class. All members are public by default. – Ryan Cavanaugh Nov 19 '13 at 15:53
  • Ok, thanks. It's definitely weird to me that it's export instead of public. I understand that what happens in javascript is a bit different, but still public should then implicitly mean export too I think. – David Thielen Nov 19 '13 at 17:10
  • Really good answer of a confusing topic! maybe top level export should have a different name, even if maybe there are low level similarities look like an important difference and compiler error are also not clear. – Olmo Nov 24 '13 at 11:28
  • Does the module itself ever need to have the export qualifier? – David Thielen Apr 15 '14 at 15:04
3

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

basarat
  • 261,912
  • 58
  • 460
  • 511