【问题标题】:Unexpected leading underscore with babel's playgroundbabel's playground 意外的前导下划线
【发布时间】:2016-10-27 01:52:00
【问题描述】:

看看下面的类“数据”方法。方法体包含 一个名为“result”的变量,并在 else if 子句中重新分配给一个数组。

出于某种原因,babel 使用前导下划线转换上述变量。

ES6 类:

class Serie {
  constructor( name, data = [] ) {
    Object.defineProperty(this, "name", {
      enumerable: false,
      configurable: false,
      writable: false,
      value: name
    })

    data.map( (v, i) => this[v.name] = v.value );
  }

  data( name ) {
    let result = null;

    if ( arguments.length == 1 ) {
      result = this.hasOwnProperty( name ) ? this[ name ] : result;
    }
    else if ( arguments.length == 0 ) {
      let keys   = Object.keys(this),
          i      = keys.length,
          result = [];

      while ( i-- ) {
        result.push( this[ keys[i] ] );
      }
    }

    return result;
  }

  // ...
}

转译的方法:

function data(name) {
      var result = null;

      if (arguments.length == 1) {
        result = this.hasOwnProperty(name) ? this[name] : result;
      } else if (arguments.length == 0) {
        var keys = Object.keys(this),
            i = keys.length,
            _result = [];

        while (i--) {
          _result.push(this[keys[i]]);
        }
      }

      return result;
    }

【问题讨论】:

    标签: javascript ecmascript-6 babeljs transpiler


    【解决方案1】:

    result 正在被重新声明,而不仅仅是重新分配,使用let,因此范围仅限于当前块(else if 块)。

    当转译为 var 时,它不遵守块作用域,第二个声明不应覆盖第一个。

    基本上就是这样的区别:

    let a = 123;
    if (true) {
      let a = 456;
    }
    // a === 123
    

    还有这个:

    var a = 123;
    if (true) {
      var a = 456;
    }
    // a === 456
    

    【讨论】:

    • 哦,废话!我完全错过了。谢谢。
    猜你喜欢
    • 2014-02-08
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多