2015-06-11 81 views
0

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()不是一個函數調用?

回答

2

這是一個運算符優先級的例子。您使用的操作員具有以下優先權:&&||,=,,

這意味着var ... = ... && ...相當於var ... = (... && ...),但var ... = ... , ....相當於(var ... = ...) , ....

例如,您可以檢查優先級here

2

此代碼首先受讓人,然後調用

(window.testTwo = function testTwo() { 
    alert("Test two"); 
}) && testTwo(); 
  1. 分配window.testTwo = function testTwo() { alert("Test two") };
  2. 呼叫testTwo()

但這另一種嘗試分配

window.testThree = function testThree() { 
    alert("Test three"); 
} && testThree(); 
之前調用
  1. 評估函數表達式(不聲明,所以沒有創建testThree變量!)function testThree() { alert("Test three") }
  2. 呼叫和分配window.testThree = testThree();

然而,testThree是未申報。所以會引發錯誤。