为什么 babel 将导入的函数调用重写为 (0, fn)(...)? [英] Why does babel rewrite imported function call to (0, fn)(...)?

查看:18
本文介绍了为什么 babel 将导入的函数调用重写为 (0, fn)(...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个输入文件

import { a } from 'b';

function x () {
  a()
}

babel 会编译成

'use strict';

var _b = require('b');

function x() {
  (0, _b.a)();
}

但是在松散模式下编译时,函数调用输出为 _b.a();

but when compiled in loose mode the function call is output as _b.a();

我已经对添加逗号运算符的位置进行了一些研究,希望有评论对其进行解释.负责添加它的代码是这里.

I've done some research into where the comma operator is added in the hope there was a comment explaining it. The code responsible for adding it is here.

推荐答案

(0, _b.a)() 确保函数 _b.a 被调用this 设置为全局对象(或者如果启用了严格模式,则设置为 undefined).如果您要直接调用 _b.a(),则在调用 _b.a 时将 this 设置为 _b>.

(0, _b.a)() ensures that the function _b.a is called with this set to the global object (or if strict mode is enabled, to undefined). If you were to call _b.a() directly, then _b.a is called with this set to _b.

(0, _b.a)(); 等价于

0; // Ignore result
var tmp = _b.a;
tmp();

(, 是逗号操作符,参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator).

(the , is the comma operator, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator).

这篇关于为什么 babel 将导入的函数调用重写为 (0, fn)(...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆