【问题标题】:How Babel transpiles the rest/spread operatorBabel 如何转换 rest/spread 运算符
【发布时间】:2020-02-11 18:26:24
【问题描述】:

我想知道 Babel 是如何转译这段代码的?

const test = ({ val1, val2, ...rest }) => val1.toLowerCase();

test({
  val1: 'Test',
  val2: 'other',
  o1: 'other',
  o2: 'Another'
});

这是一个虚拟函数,它获取一个对象作为参数并返回val1 toLowerCase。所以没什么神奇的。

【问题讨论】:

    标签: javascript ecmascript-6 babeljs transpiler


    【解决方案1】:

    没那么复杂。它将创建一个排除属性数组,例如:['val1', 'val2'],并将整个对象和排除数组传递给函数:

    var test = function test(_ref) {
    var val1 = _ref.val1,
      val2 = _ref.val2,
      rest = _objectWithoutProperties(_ref, ["val1", "val2"]);
      return val1.toLowerCase();
    };
    

    _objectWithoutProperties的实现是这样的:

    function _objectWithoutProperties(source, excluded) {
      if (source == null) return {};
      // This does the trick
      var target = _objectWithoutPropertiesLoose(source, excluded);
    
      var key, i;
      // If the object keys were Symbols it will append them too. 
      // If we don't have any symbols this was unnecessary
      if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
        for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];
          if (excluded.indexOf(key) >= 0) continue;
          if (
            !Object.prototype.propertyIsEnumerable.call(source, key)
          ) continue;
          target[key] = source[key];
        }
      }
      return target;
    }
    

    最后_objectWithoutPropertiesLoose 的实现是这样的:

    function _objectWithoutPropertiesLoose(source, excluded) {
      // if the source object was null so there's nothing to return
      if (source == null) return {};
    
      // initialize an empty object to assign values to it later 
      var target = {};
    
      // get an array of keys from the source object and loop through it
      var sourceKeys = Object.keys(source);
    
      var key, i;
      for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];
    
        // THIS IS WHERE IT HAPPENS: if the current key was present on the excluded array, so skip this iteration
        if (excluded.indexOf(key) >= 0) continue;
    
        // add the value with that key into the target object
        target[key] = source[key];
      }
    
      // return the target object
      return target;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 1970-01-01
      • 2017-08-28
      • 2018-09-12
      • 2018-12-21
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多