内部模块作为单一功能 [英] Internal module as single function

查看:73
本文介绍了内部模块作为单一功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 TS 生成两个函数,而不生成一个?

Why TS generates two functions, but not one?

看起来我们在 TS 中的两个文件之间有一个模块:

It looks like we have one module separated between two files in TS:

module Main {
    export function P() {
    }
}
module Main {
    export function P2() {
         P();
    }
}

它作为两个函数编译为 JS:

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 = {}));

但是我需要这样的 JS 输出文件,所以所有模块的内容都会被连接到单个函数中:

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.

我知道我可以写:

module Main {
    function F1() {
    }
    export function F2() {
        F1();
    }
}

但这不是一个好主意,因为有时我有非常大的类和函数.

But it is not a good idea, because sometimes I have very big classes and functions.

推荐答案

为什么 TS 生成两个函数,而不生成一个

Why TS generates two functions, but not one

只是一个优化不是由编译器完成.基本上是 module 关键字(现在称为 namespace) 是一个简单的转换一种常见的命名空间模式.特别是基于立即调用的函数表达式 (IIFE) 的命名空间.

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.

这篇关于内部模块作为单一功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆