以下TypeScript:
enum PrimaryColors { Red, Green, Blue };
生成以下JavaScript:
var PrimaryColors; (function (PrimaryColors) { PrimaryColors[PrimaryColors["Red"] = 0] = "Red"; PrimaryColors[PrimaryColors["Green"] = 1] = "Green"; PrimaryColors[PrimaryColors["Blue"] = 2] = "Blue"; })(PrimaryColors || (PrimaryColors = {})); ;
我很尴尬地承认我不明白JavaScript在做什么.
括号中的函数使用另一个赋值作为索引/键来分配字符串值.我之前没见过这样的东西.
那个函数后面的(PrimaryColors ||(PrimaryColors = {})的目的是什么?
如果答案是正确学习JavaScript,我会很乐意接受它,只要它附带一个明确解释我所看到的内容的建议来源这里.
我相信:
PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
相当于:
PrimaryColors[0] = "Red"; PrimaryColors["Red"] = 0;
请参阅此参考.
表达式x = 7是第一类型的示例.该表达式使用=运算符将值7赋给变量x.表达式本身的评估结果为7.
例如:
console.log((x = 7));
输出:
7
同理:
var x = {}; console.log((x["hi"] = 7));
还输出7.
至于第二件事,PrimaryColors
最初是未定义的.
var x; console.log(x); // undefined
在布尔上下文中,undefined
求值为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),它将传递{}
给函数.
PrimaryColors || (PrimaryColors = {})
也许这会有所帮助.
(function() {})();
这是一个"立即执行的功能".它将函数定义为表达式,然后调用它.
var x = y || y = {};
如果用于将某些内容初始化为默认值的常见模式.如果y没有值,则or-statement的第1部分为false,因此它执行第2部分,该部分为y赋值.第二个表达式的值是y的新值.因此x变为y的值 - 如果尚未定义,则为新值.
x[y] = z;
JS中的对象是关联数组.换句话说,字符串 - 对象对,如IDictionary(字符串,对象).此表达式在字典x中将值y设置为z的值;
x[x["a"] = 0] = "a";
所以,同样的事情,但有一个嵌套的表达式,这是:
x["a"] = 0;
所以只设置键"a"的值.没有什么花哨.但这也是一个表达式,其值为0.所以在原始表达式中替换它:
x[0] = "a";
键需要是字符串,所以它实际上是相同的:
x["0"] = "a";
这只是设置字典中的另一个键.结果是这些陈述是真的:
x["0"] === "a"; x["a"] === 0;