Internal module as single function

可紊 提交于 2019-12-11 08:35:03

问题


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

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