为什么TypeScript为类生成IIFE? [英] Why is TypeScript generating an IIFE for a class?

查看:140
本文介绍了为什么TypeScript为类生成IIFE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的TypeScript代码:

Looking at this TypeScript code:

class Greeter {
    greet() {}
}

它围绕构造函数和所有原型函数声明生成IIFE(立即调用函数表达式) :

It generates an IIFE (Immediately-Invoked Function Expression) around the constructor function and all prototype function declarations like:

var Greeter = (function () {
    function Greeter() {
    }
    Greeter.prototype.greet = function () { };
    return Greeter;
}());

这里有什么优势?每当我阅读有关IIFE的文章时,我都会在定义模块时看到很多用法。据我所知,Typescript不会在IIFE中生成任何会污染全局名称空间的东西。

What is the advantage here? When ever I read about IIFE I see a lot usage in defining modules. As far as I can see Typescript does not generate anything inside the IIFE that would pollute the global namespace.

在我看来,这种类声明没有任何优势:

In my opinion there is no advantage over this class declaration:

var Greeter = function () {}
Greeter.prototype.greet = function () { };

原因是什么?

推荐答案

这很有趣。我认为打字稿编译器通过将表达式分配给作用域中的变量来编译从 ClassExpression s推导出的 ClassDeclaration 。他们不必独立处理这些案件。这样可以简化TypeScript编译器,并使生成的代码具有一定的模块化(我想说的是更具可读性,但这只是一个问题)。

That is interesting. I think the typescript compiler compiles ClassDeclaration deduced from ClassExpressions, by assigning the expression to a variable in the scope, so they don't have to handle those cases independently. This simplifies the TypeScript compiler, and makes the generated code somewhat modular (I would say more readable, but that's just a matter of taste).

class Bar { };
foo(class Baz { });
var Baa = class Bab { };

编译为:

var Bar = (function () {
    function Bar() {
    }
    return Bar;
}());
;
foo((function () {
    function Baz() {
    }
    return Baz;
}()));
var Baa = (function () {
    function Bab() {
    }
    return Bab;
}());

请参见 ClassDeclaration 编译为 ClassExpression 分配给局部变量。

See, the ClassDeclaration is compiled as a ClassExpression assigned to a local variable.

这篇关于为什么TypeScript为类生成IIFE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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