问题
Why TS generates two functions, but not one?
It looks like we have one module separated between two files in TS:
module Main {
export function P() {
}
}
module Main {
export function P2() {
P();
}
}
And it compile to JS as two functions:
var Main;
(function (Main) {
function P() {
}
Main.P = P;
})(Main || (Main = {}));
var Main;
(function (Main) {
function P2() {
Main.P();
}
Main.P2 = P2;
})(Main || (Main = {}));
But I need such JS output file, so all modules content would be concatenated to single function:
var Main;
(function (Main) {
function P() {
}
function P2() {
P();
}
Main.P2 = P2;
})(Main || (Main = {}));
So I do not need to write additional export function to use in other parts of module with same name.
I know that I can write:
module Main {
function F1() {
}
export function F2() {
F1();
}
}
But it is not a good idea, because sometimes I have very big classes and functions.
回答1:
Why TS generates two functions, but not one
Just an optimization not done by the compiler. Basically the module
keyword (now called namespace) is a simple transform to a common namespacing pattern. Specifically Immediately-invoked Function Expressions (IIFE)s
based namespacing.
来源:https://stackoverflow.com/questions/32569220/internal-module-as-single-function