Home > Article > Backend Development > Analysis of comma operator in js
This article mainly introduces the analysis of the comma operator in js, which has certain reference value. Now I share it with you. Friends in need can refer to it
Overview: The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. The comma operator can be used when you want to include multiple expressions where one expression is expected. One of the most common uses of this operator is when multiple parameters are provided in a for loop. Note that the comma in the var statement is not a comma operator because it is not present in an expression.
Case:
function testFunc () { var a = 0; return (a += 1, a); // 等价于return ++x; } console.log((1, 2)); // console 2 console.log((a = b = 3, c = 4)); // console 4
Let’s look at a case first:
var obj = { myFunc: function () { console.log(this === window); console.log(this === obj); } } obj.myFunc(); // false true (0,obj.myFunc)(); // true
The output result is false-true ture.
In function foo, this points to a, because foo is a method of a. So it can be understood that this===window returns false.
But calling (0,obj.myFunc)(), the expression (0,a.foo) will evaluate each of its operands (from left to right) and return the value of the last operand. In other words, (0, a.foo) is equal to:
function(){ console.log(this === window);//且这个函数不再附加到任何东西,它this是全局对象window,所以输出的是true。
The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
The above is the detailed content of Analysis of comma operator in js. For more information, please follow other related articles on the PHP Chinese website!