Reputation: 150996
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?
Upvotes: 4
Views: 59
Reputation: 20150
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.
Upvotes: 3