JavaScript逗号分隔函数是什么意思?

5

我正在阅读一个JavaScript Dojo库,看到很多我无法理解的复杂函数。例如:

_refreshUI: function () {
    this._hasUI && (g.empty(this.flowContainer), f.forEach(this.basemaps, function (a, b) { a.id || (a.id = "basemap_" + b); this.flowContainer.appendChild(this._buildNodeLayout(a))
}, this), g.create("br", { style: { clear: "both" } }, this.flowContainer), this._markSelected(this._selectedBasemap))

这个函数是单行编写的。它包含用逗号分隔的函数。因此我无法阅读它。

我不询问上述函数的作用。

这是什么意思?

this._hasUI && (firstFunction, secondFunction, ...)

它是做什么的?或者说,如何更加清晰地表达它?


如果 this._hasUI 为真,则调用函数。请查看 逻辑运算符逗号运算符 - Givi
1
它与jsFiddle相同。 - Givi
2个回答

11

如果this._hasUI为true,这是仅执行函数的一种方式。

请尝试此方法:

true && (console.log(1), console.log(2));

还有这个:

false && (console.log(1), console.log(2));

你会发现只有第一行代码会运行 console.log() 函数。

这是因为布尔运算符 AND (&&) 是惰性求值的。如果运算符左侧解析为 false,解释器就不会计算右侧,因为这个操作永远不能得出 true。这意味着右侧的函数只有在左侧是 truthy 值 时才会执行。


5
为了让答案更完整,语法 (function1, function2) 会依次执行两个函数,并返回 function2 的返回值,无论 function1 返回什么。 - dev4life
2
@user2070775,我认为你的评论更符合我想象中的OP所问的内容。 - frezq

0

让我们把这个放到一个对象里面,为了可读性,我用括号将函数包起来:

var myObj = {
    _hasUI : true,
    _markSelected : function(arg){some logic}
    _refreshUI: function() {
                 this._hasUI &&  
                 (
                      // Strat evaluation from the left to right
                                 (g.empty(this.flowContainer), 
                                 (f.forEach(...)                ), 
                                 (g.create(args)                ), 
                                 (this._markSelected(arg)   )
                     // End evaluation and return
                     // the result of this._markSelected(arg)
                 )
}


基本上,这意味着如果 this._hasUI 为 true,则 继续 执行后面的内容。在这种情况下,执行/评估第一个函数,然后是第二个函数... 直到最后一个函数,并且只会返回最后一个函数的结果
你可以找到其他东西,不仅仅是函数,你可以找到比较变量和任何表达式...
看看整数的相同代码:
var secondExempleObj = {
    _hasUI : true, // change it to false and see the difference
    _refreshUI: function () {
        return ( this._hasUI && (1,false,3,4) )
    }
}
console.log('result : ' + secongExempleObj ._refreshUI());
// if _hasUI == true then the resutl will be 4
// if _hasUI  == false you will get false
// _hasUI  will work just like light switch if true -> continue to evaluate the rest of expressions else get out of there so we can replace it like so

var thirdObj  = {
    numbers : [1,87,30],
    sumFunction : function(n1,n2,n3){ console.log(n1+n2+n3) },
    _hasUI : true,
    _refreshUI: function () {
        if(this._hasUI == true){          
            return (1,false,this.sumFunction(...this.numbers),4)
       }else{
           return false;
       }
   }
}
console.log('result  : ' + thirdObj._refreshUI());
// it will console log 118 then 4 
// if you switch _hasUI to false it will logout false

希望这对你有意义


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接