简体   繁体   中英

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

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

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. Evidently Traceur does not have this optimization. I'm not sure why either one wouldn't only use the local variable when the destructured variable is actually being re-bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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