理解JavaScript逗号运算符

时间:2015-06-11 14:27:52

标签: javascript operators comma

This article by Angus Croll解释了这个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 个答案:

答案 0 :(得分:2)

这是运营商优先的情况。您使用的运算符具有以下优先级:function fn() { fn.obj = { result: true }; return fn.obj.result; } console.log(fn()); console.log(fn.obj.result); &&||=

这意味着,相当于var ... = ... && ...,但var ... = (... && ...)相当于var ... = ... , ....

例如,您可以检查优先级here

答案 1 :(得分:2)

此代码首先分配然后调用

(window.testTwo = function testTwo() {
    alert("Test two");
}) && testTwo();
  1. 分配window.testTwo = function testTwo() { alert("Test two") };
  2. 致电testTwo()
  3. 但另一个人试图在作业之前调用

    window.testThree = function testThree() {
        alert("Test three");
    } && testThree();
    
    1. 评估函数表达式(不是声明,因此不会创建testThree变量!)function testThree() { alert("Test three") }
    2. 致电并指定window.testThree = testThree();
    3. 但是,testThree未声明。因此会抛出错误。