This kind of code is typically generated by transpilers (like Babel), in order to convert modern JavaScript -- that uses the most recent additions to the specification -- to a JavaScript version that is more widely supported.
(此类代码通常由编译器(如Babel)生成,以将现代JavaScript(使用该规范的最新功能)转换为得到更广泛支持的JavaScript版本。)
Here is an example where this transpilation pattern occurs:
(这是发生这种转嫁方式的一个例子:)
Let's say we have this original code before transpilation:
(假设在转译之前我们有以下原始代码:)
import {myfunc} from "mymodule";
myfunc();
To make this ES5-compatible code, you could do this:
(要制作与ES5兼容的代码,您可以执行以下操作:)
"use strict";
var mymodule = require("mymodule");
mymodule.myfunc();
But here we would execute myfunc
with mymodule
as this
value, which is not happening in the original code.
(但是这里我们将使用mymodule
作为this
值执行myfunc
,这在原始代码中不会发生。)
And although that might not always be an issue, it is better to make sure the function behaves just like it would in the original version , even if that function would use a this
reference -- how unusual or even useless that use of this
in myfunc
might be (because also in the original version it would be undefined
). (虽然可能不会永远是一个问题,这是更好地确保功能的行为就像它会在原来的版本 ,即使该函数将使用this
参考-如何不寻常的,甚至没用,以至于使用this
在myfunc
可能是(因为在原始版本中也将是undefined
)。)
So for instance, if the original code would throw an error because of a this.memberFun()
reference in the function, it will also throw in the transpiled version.
(因此,例如,如果原始代码由于函数中的this.memberFun()
引用而引发错误,则它还将引发已编译的版本。)
So that is were the comma operator is used to get rid of that difference:
(这就是使用逗号运算符消除该差异的原因:)
(0, mymodule.myfunc)();
Granted, in code that you write yourself, you would never have a good use case for this pattern, as you would not use this
in myfunc
in the first place.
(当然,在您自己编写的代码中,您永远不会有这种模式的好用例,因为您一开始就不会在myfunc
中使用this
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…