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()
不是一个函数调用?