typescript enum反编译函数如何一次创建2个键值对?

How does typescript enum trans-compilation function create 2 keyvalue pairs at once?

在打字稿中:

http://www.typescriptlang.org/Playground

enum Role {Employee = 3, Manager =5, Admin = 7}
console.log('Roles:', Role[3])

转译为:

var Role;
(function (Role) {
    Role[Role["Employee"] = 3] = "Employee";
    Role[Role["Manager"] = 5] = "Manager";
    Role[Role["Admin"] = 7] = "Admin";
})(Role || (Role = {}));
console.log('Roles:', Role[3]);

我只是不明白这个函数是如何工作的。

1.如何一次创建 2 key:value 对,请在此处查看:

2。为什么scope传入(Role || (Role = {})?

How is it creating 2 key:value pairs at once check out here:

让我们接电话:

Role[Role["Employee"] = 3] = "Employee";

首先我们得到:

Role["Employee"] = 3

然后我们得到

Role[3] = "Employee";

其中 3 是表达式 Role["Employee"] = 3

的结果

因此您可以使用枚举将数字转换为字符串或将字符串转换为数字

Why does the scope pass in (Role || (Role = {})?

它允许您将枚举定义拆分到多个 TypeScript 文件中。

更多

书中的整个章节:https://basarat.gitbooks.io/typescript/content/docs/enums.html

评估时:

Role[Role["Employee"] = 3] = "Employee";

内部:

Role["Employee"] = 3

Role.Employee 设置为 3,但此赋值也 returns 值 3。因此,在评估作业后,实际上您剩下的是:

Role[3] = "Employee";

有关详细信息,请参阅赋值运算符 specs

在末尾 (Role || (Role = {}),计算结果为 {}。这保证了传递给函数的对象 Role 不会因任何原因 null