简体   繁体   English

为什么这个JavaScript有效?

[英]Why does this JavaScript work?

I was looking at the output of some stuff from UglifyJS and happened across some code like the following: 我正在查看来自UglifyJS的一些内容的输出,并发生在以下代码中:

var a = 0;
var b = function () {
    return function () {
        a++;
    }(), 'Hello, World'
}();

After running that code a is 1 and b is the string Hello, World! 运行该代码后, a1b为字符串Hello, World! .

At first glance it appears that b will be undefined since it looks like the result of a function with no return value is being returned, but that is followed by a comma and a string literal. 乍一看,似乎b将是undefined因为它看起来像返回没有返回值的函数的结果,但后面跟着一个逗号和一个字符串文字。

Why does this work? 为什么这样做?
And why doesn't UglifyJS just execute the anonymous function and then return Hello, World! 为什么UglifyJS不执行匿名函数然后返回Hello, World! as the next statement? 作为下一个声明?

It works due to the comma operator. 它由于逗号运算符而起作用。 From the MDN specs: 从MDN规范:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. 逗号运算符计算其两个操作数(从左到右)并返回第二个操作数的值。

Both functions are IFFYs, they are inmediately executed. 这两个函数都是IFFY,它们是在中间执行的。

The result of an expression using the comma operator is the right hand side of the comma operator. 使用逗号运算符的表达式的结果是逗号运算符的右侧。

You have: 你有:

return a_function_call(), a_string

… so you get a_string assigned. ...所以你分配了a_string

First of all let me cite MDN on the comma operator : 首先让我在逗号运算符上引用MDN

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. 逗号运算符计算其两个操作数(从左到右)并返回第二个操作数的值。

With that being said, it is clear, how your code evaluates: 话虽如此,很明显,您的代码如何评估:

Inside the immediately executed function you return 2 values separated by a comma: 在立即执行的函数内,您返回以逗号分隔的2个值:

function () { a++; }()

and

'Hello World'

So both operands are evaluated. 因此评估两个操作数。 This increments your variable a and leads to the following expression for the return value of the function to create b : 这会增加变量a并导致以下表达式为创建b的函数的返回值:

undefined, 'Hello World'

Finally the right operand is returned as a value for the outer function, thus giving b the value 'Hello World' . 最后,右操作数作为外部函数的值返回,从而给b'Hello World'

Check out the comma operator in JavaScript . 在JavaScript中查看逗号运算符

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. 逗号运算符计算其两个操作数(从左到右)并返回第二个操作数的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM