This article by Angus Croll解釋JavaScript的逗號操作是這樣的:瞭解JavaScript逗號操作
//(LHE: left hand expression, RHE right hand expression)
LHE && RHE
1. Always evaluate LHE
2. If LHE is true, evaluate RHE
LHE || RHE
1. Always evaluate LHE
2. If LHE is false, evaluate RHE
LHE, RHE
1. Always evaluate LHE
2. Always evaluate RHE
不過,我已經做了的jsfiddle測試enter link description here與下面的代碼,並出現了LHE必須用括號如果被包圍運營商是&&
。
// Works fine
(function one(window) {
window.testOne = function testOne() {
alert("Test one");
}, testOne();
})(window);
// Works, but JSHint complains at *:
// "Expected an assignment or function call but saw instead an expression"
(function two(window) {
(window.testTwo = function testTwo() {
alert("Test two");
}) && testTwo(); // *
})(window);
// Looks good to JSHint, but fails at runtime:
// "ReferenceError: Can't find variable: testThree"
(function three(window) {
window.testThree = function testThree() {
alert("Test three");
} && testThree();
})(window);
你能解釋爲什麼testOne
(使用,
)不需要周圍的第一個表達式括號,但testTwo
(使用&&
)呢?爲什麼JSHint認爲test()
不是一個函數調用?