简体   繁体   English

当 Babel 和 Traceur 转译 ES6 解构时,额外变量的目的是什么?

[英]What is the purpose of an extra variable when Babel and Traceur transpile an ES6 destructure?

Both Babel and Traceur would transpile for the following code Babel 和 Traceur 都会转译以下代码

obj = {
    fullName: "Peter",
    say() {
        console.log("My name is", this.fullName);
    }
};

let { fullName, say } = obj;

as作为

"use strict";

obj = {
  fullName: "Peter",
  say: function say() {
    console.log("My name is", this.fullName);
  }
};
var _obj = obj,
    fullName = _obj.fullName,
    say = _obj.say;

(Traceur uses the name $__1 ) the introduction of a new variable _obj seems totally unnecessary. (Traceur 使用名称$__1 )引入新变量_obj似乎完全没有必要。 What is a reason that they both do that?他们俩这样做的原因是什么?

When destructuring a variable declared with var it is possible to reassign the variable containing the value you are currently destructuring.解构用var声明的变量时,可以重新分配包含您当前正在解构的值的变量。

var foo = { foo: 1, bar: 2 };
var {foo, bar} = foo;
console.log(`foo: ${foo}, bar: ${bar}`);
// outputs "foo: 1, bar: 2"

If this were naively transpiled without creating a temporary variable the variable foo would be altered, before the value for bar is retrieved:如果在没有创建临时变量的情况下天真地转换了变量 foo 将在检索 bar 的值之前更改:

var foo = { foo: 1, bar: 2 };
var foo = foo.foo;
var bar = foo.bar;
console.log(`foo: ${foo}, bar: ${bar}`);
// outputs "foo: 1, bar: undefined"

My guess is that Babel has an optimization where it recognizes this as not necessary with let bindings, because then you would have an error at the point of re-binding of the same variable.我的猜测是 Babel 有一个优化,它认为这对于let绑定是不必要的,因为那样你会在重新绑定同一变量时出错。 Evidently Traceur does not have this optimization.显然 Traceur 没有这种优化。 I'm not sure why either one wouldn't only use the local variable when the destructured variable is actually being re-bound.我不确定为什么当解构变量实际上被重新绑定时,为什么任何一个人都不会只使用局部变量。

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

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