简体   繁体   English

命名空间内的匿名函数

[英]anonymous function inside namespace

I'm learning Typescript but I'm having a few issues trying to understand a few things. 我正在学习打字稿,但在尝试理解一些东西时遇到了一些问题。

I have seen this code: 我看过这段代码:

module Games {

((): void => {

    alert("");
);
})();
}

but when complied to javascript I get the same result if I change it to the bellow: 但是当使用javascript时,如果将其更改为以下内容,则会得到相同的结果:

module Games {

    alert("");
})();
}

Is there any reason why I would write something like in the first example, or is it just bad code. 是否有任何理由为什么我要编写第一个示例中的内容,还是仅仅是错误的代码?

In your example, there is no reason to do that. 在您的示例中,没有理由这样做。

In more general terms, setting up a function creates a local scope, which allows you to use variables with it in that are not accessible to the rest of the module. 用更笼统的术语来说,设置一个函数会创建一个局部作用域,该作用域允许您在模块的其余部分无法使用的变量中使用它。 This reduces the risk of variables in different parts of the module overwriting each other because they share a name. 这降低了模块不同部分中的变量彼此共享的风险,因为它们共享一个名称。

So starting with this working example... 所以从这个工作示例开始...

module Games {
    ((): void => {
        alert("");
    })();
}

You currently end up with the following result when you compile your TypeScript to JavaScript - the module becomes and immediately invoked function expression... 当您将TypeScript编译为JavaScript时, 当前会得到以下结果-模块变为并立即调用函数表达式...

var Games;
(function (Games) {
    (function () {
        alert("");
    })();
})(Games || (Games = {}));

Later on when you are targeting a later version of ECMAScript, you may find that the module is actually there in the JavaScript (as this is just early access to a feature that is planned for ECMAScript). 稍后,当您以更高版本的ECMAScript为目标时,您可能会发现该模块实际上位于JavaScript中(因为这只是对ECMAScript计划的功能的早期访问)。

Unless you have a good reason to want that within the module, I would recommend the following adjustment... 除非您有充分的理由希望在模块中使用它,否则我建议进行以下调整...

module Games {

}

((): void => {
    alert("");
})();

I think this will survive future changes better. 我认为这将更好地适应未来的变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM