Why does this JavaScript work?

怎甘沉沦 提交于 2019-12-30 16:21:31

问题


I was looking at the output of some stuff from UglifyJS and happened across some code like the following:

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!.

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.

Why does this work?
And why doesn't UglifyJS just execute the anonymous function and then return Hello, World! as the next statement?


回答1:


It works due to the comma operator. From the MDN specs:

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.




回答2:


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.




回答3:


First of all let me cite MDN on the comma operator:

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:

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:

undefined, 'Hello World'

Finally the right operand is returned as a value for the outer function, thus giving b the value 'Hello World'.




回答4:


Check out the comma operator in JavaScript.

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.



来源:https://stackoverflow.com/questions/13090434/why-does-this-javascript-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!