10.6 Code Generation

A namespace generates JavaScript code that is equivalent to the following:

  1. var <NamespaceName>;
  2. (function(<NamespaceName>) {
  3. <NamespaceStatements>
  4. })(<NamespaceName>||(<NamespaceName>={}));

where NamespaceName is the name of the namespace and NamespaceStatements is the code generated for the statements in the namespace body. The NamespaceName function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire namespace is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn’t create and return a namespace instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that namespaces can extend each other.

An import statement generates code of the form

  1. var <Alias> = <EntityName>;

This code is emitted only if the imported entity is referenced as a PrimaryExpression somewhere in the body of the importing namespace. If an imported entity is referenced only as a TypeName or NamespaceName, nothing is emitted. This ensures that types declared in one namespace can be referenced through an import alias in another namespace with no run-time overhead.

When a variable is exported, all references to the variable in the body of the namespace are replaced with

  1. <NamespaceName>.<VariableName>

This effectively promotes the variable to be a property on the namespace instance and ensures that all references to the variable become references to the property.

When a function, class, enum, or namespace is exported, the code generated for the entity is followed by an assignment statement of the form

  1. <NamespaceName>.<EntityName> = <EntityName>;

This copies a reference to the entity into a property on the namespace instance.