TypeScript中的枚举:什么是JavaScript代码? [英] Enums in TypeScript: what is the JavaScript code doing?
问题描述
以下TypeScript:
The following TypeScript:
enum PrimaryColors { Red, Green, Blue };
生成以下JavaScript:
Produces the following JavaScript:
var PrimaryColors;
(function (PrimaryColors) {
PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
PrimaryColors[PrimaryColors["Green"] = 1] = "Green";
PrimaryColors[PrimaryColors["Blue"] = 2] = "Blue";
})(PrimaryColors || (PrimaryColors = {}));
;
我很尴尬地承认我不明白JavaScript在做什么。
括号中的函数是使用另一个赋值作为索引/键分配字符串值。我以前没有看到过这样的东西。
跟随函数的(PrimaryColors = {})的目的是什么?
如果答案是要学习JavaScript正确,我会很容易接受,只要它附带一个清楚地解释我在这里看到的内容的建议的源。
I am embarrassed to admit that I don't understand what the JavaScript is doing.
The function in parentheses is assigning string values using another assignment as the index/key. I have not seen anything like this before.
And what is the purpose of the (PrimaryColors || (PrimaryColors = {}) following the function?
If the answer is to learn JavaScript properly, I will readily accept it, provided it comes with a suggested source that clearly explains what I am seeing here.
推荐答案
我相信:
PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
相当于:
PrimaryColors[0] = "Red";
PrimaryColors["Red"] = 0;
< >请参阅参考。
表达式x = 7是第一个类型的示例,该表达式
使用=运算符将值七分配给变量x
表达式本身评估
The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x. The expression itself evaluates to seven.
例如:
console.log((x = 7));
输出:
7
同样:
var x = {};
console.log((x["hi"] = 7));
还输出7。
对于第二件事, PrimaryColors
最初未定义。
As for the second thing, PrimaryColors
is initially undefined.
var x;
console.log(x); // undefined
在布尔上下文中, undefined
评估为 false
:
In a boolean context, undefined
evaluates to false
:
console.log(!undefined); // true
console.log(!!undefined); // false
理性检查:
console.log((!undefined) === true); // true
console.log((!!undefined) === false); // true
console.log(undefined === false); // false
这是短路的常见用法。因为 PrimaryColors
最初未定义(false),它将通过 {}
到该函数。
This is a common usage of short circuiting. Because PrimaryColors
is initially undefined (false), it will pass {}
to the function.
PrimaryColors || (PrimaryColors = {})
这篇关于TypeScript中的枚举:什么是JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!