前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于Babel 6的 loose mode

关于Babel 6的 loose mode

作者头像
用户1515472
发布2019-07-24 14:19:42
6300
发布2019-07-24 14:19:42
举报

1.Overview

loose mode 我翻译为松散模式,loose mode在babel中通常是不推荐使用的,但是我们需要知道的是使用 loose mode 转换而来的代码更加像ES5的代码(更像是人手写的)

大多数Babel插件都有两种模式 normal modeloose modenormal mode 转换而来的ES5代码更加符合ECMAScript 6 的语义,而 loose mode 转换而来的代码更加简单,更像是人写的。

loose mode 的优点在于兼容旧引擎,可能会更加快,缺点在于如果我们需要将转换之后的代码重新转换为 native ES6 代码,可能会遇到问题,而这个冒险在大多数时候是不值得的。

2.Examples

以ES6的class为例,我们编写以下代码:

代码语言:javascript
复制
class person {
  constractor(name, age) {
    this.name = name;
    this.age = age;
  }
  getName(){
    return this.name;
  }
  getAge(){
  	  return this.age;
  }
}

normal mode 下转换为:

代码语言:javascript
复制
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var person = function () {
  function person() {
    _classCallCheck(this, person);
  }

  _createClass(person, [{
    key: "constractor",
    value: function constractor(name, age) {
      this.name = name;
      this.age = age;
    }
  }, {
    key: "getName",
    value: function getName() {
      return this.name;
    }
  }, {
    key: "getAge",
    value: function getAge() {
      return this.age;
    }
  }]);

  return person;
}();

loose mode 下转换为:

代码语言:javascript
复制
"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var person = function () {
  function person() {
    _classCallCheck(this, person);
  }

  person.prototype.constractor = function constractor(name, age) {
    this.name = name;
    this.age = age;
  };

  person.prototype.getName = function getName() {
    return this.name;
  };

  person.prototype.getAge = function getAge() {
    return this.age;
  };

  return person;
}();

可以看到,非常直观的是 loose mode 下的代码更加像是人手写的。尽管如此,但是仍然不推荐使用 loose mode

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.Overview
  • 2.Examples
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档