2015-06-11 53 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是未申报。所以会引发错误。