Cam*_*tin 12 javascript syntax colon
我正在创建一个库,我经常检查Closure Compiler输出的结果,看看它是如何做的(我确实有单元测试,但我仍然希望看到编译代码以获得更好的压缩方式的提示).
所以,我发现了这段非常奇怪的代码,这是我以前从未见过的.
variable : {
some();
code()
}
Run Code Online (Sandbox Code Playgroud)
注意:这不是对象文字!此外,没有?任何地方,将使它一个?:条件.
该代码位于常规功能块(IIFE)中.
variable在这种情况下,是一个未定义的变量.没有任何代码可以将它变为真,假,或其他任何东西,只是为了确保,我把它console.log放在那里,的确,我得到了一个ReferenceError.
请注意我也在IE8中测试我的代码,所以这不仅仅是在现代浏览器中.它似乎是标准的,普通的旧javascript.
所以让我们试一试吧.点击Chrome的控制台,我得到了这个:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
Run Code Online (Sandbox Code Playgroud)
但是之后...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
Run Code Online (Sandbox Code Playgroud)
...和...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
Run Code Online (Sandbox Code Playgroud)
那它是做什么的?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Run Code Online (Sandbox Code Playgroud)
如果有人可以向我解释这段代码的意图,或者至少是它的作用,我会很高兴.