在我的 React 应用程序中,我使用 lodash 函数
set
,如下所示:
set(objectToSet, fieldInObjectToSet, valueToSet);
当我查看转译的代码时,我发现这一行被转换为:
(0,lodash__WEBPACK_IMPORTED_MODULE_2__.set)(objectToSet, fieldInObjectToSet, valueToSet);
这部分是什么:
(0,lodash__WEBPACK_IMPORTED_MODULE_2__.set)
?
看起来像是引用set函数的东西,但是前导的0是什么呢?这看起来也像无名函数的参数列表。这是这个吗?
谢谢!
对于类似
的图案(0, _.set)(...)
0
是任意且无关的,类似于void 0
,它实际上可以是一切。
此模式的要点是从
set
返回 _
函数并调用它,但没有调用上下文 _
。
这里的区别是微不足道的,或者根本没有区别。但转换器这样做是为了确保在没有 ES6 模块的情况下它始终具有相同的行为。
它这样做的原因是因为你这样称呼它
import { set } from 'lodash'; // or similar import
set(...);
但不是
import _ from 'lodash';
_.set(...)
为了更好地证明这种差异,这里有一个最小的例子:
window.name = 'window';
const foo = {
name: 'foo',
greeting() {
console.log(`Hello, I'm ${this.name}!`);
}
};
// this function is called with calling context of `foo`
foo.greeting(); // > hello, I'm foo
// this function is called with calling context of current scope, which is `window`
(0, foo.greeting)(); // > hello, I'm window
// which is essentially equivolent to
const { greeting } = foo;
greeting(); // > hello, I'm window
转换器使用此模式是为了确保
set
函数调用在没有 ES6 import
的情况下编译时的行为相同。