簡體   English   中英

當 Babel 和 Traceur 轉譯 ES6 解構時,額外變量的目的是什么?

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

Babel 和 Traceur 都會轉譯以下代碼

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

let { fullName, say } = obj;

作為

"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 使用名稱$__1 )引入新變量_obj似乎完全沒有必要。 他們倆這樣做的原因是什么?

解構用var聲明的變量時,可以重新分配包含您當前正在解構的值的變量。

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

如果在沒有創建臨時變量的情況下天真地轉換了變量 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"

我的猜測是 Babel 有一個優化,它認為這對於let綁定是不必要的,因為那樣你會在重新綁定同一變量時出錯。 顯然 Traceur 沒有這種優化。 我不確定為什么當解構變量實際上被重新綁定時,為什么任何一個人都不會只使用局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM