我正在做一個庫,我經常檢查Closure Compiler的輸出結果,看看它是如何做的事情(我有單元測試,但我仍然希望看到編譯代碼提示如何更好地壓縮)。請解釋這在javascript中的冒號使用
所以,我發現了這個非常奇怪的代碼,這是我從未見過的。
variable : {
some();
code()
}
注:這是不是一個對象字面!此外,沒有?
任何地方會使它a ?:
conditional。
該代碼位於常規功能塊(一個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.
但後來......
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
......還有......
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
那麼它有什麼作用?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
請問,如果有人能向我解釋這段代碼是做什麼的,或者至少它做了什麼,我很樂意。
爲什麼有人投票關閉它? –