【慕课网】带你快速入坑ES6

警告
本文最后更新于 2020-12-05,文中内容可能已过时。

讲师:谢成 课程:https://www.imooc.com/learn/1246

  • ES6 和 ES2015 指的是同一个版本
  • 安装 VSCode 编辑器的插件——Live Server(差量即时编译)
  • 常量是什么

    当前的量只可以读不可以写

  • ES5 里声明常量的方法

    Object.defineProperty(window, "es", {
      value: "es6",
      writable: false, //不可写
    });
    console.log(res); //es6
    es = "es2015";
    //不会报错
    console.log(res); //es6
    
  • ES6 声明常量要注意的

    • 声明 const 常量时就要赋值,不然会报错;

    • 通过 const 声明的常量不允许重复声明;

    • 通过 const 声明的常量不属于顶层对象 window,这样不会污染全局变量;

    • 当用 const 声明常量时,不存在变量提升,即下面所写会报错,要先定义,后使用

      console.log(str);
      const str = "es6";
      
    • const 变量具有块级作用域

  • 例 1 对象的属性被改变

    const esObj = {
      name: "es6",
      year: 2015,
    };
    esObj.name = "es2015";
    console.log(esObj); //{name:'es2015',year:2015}
    
  • 例 2 数组元素被改变

    const arr = ["es6", "es7", "es8"];
    arr[0] = "es2015";
    console.log(arr); //['es2015','es7','es8']
    
  • 数据存储类型

    • 栈存储:数字、字符串、数组或常量的等引用数据类型

    • 堆存储:数组、对象

  • 怎样使 const 声明的对象和数组内部不可改变?

    • 方法一:Object.freeze()

      • 对象和数组都可以被冻结

        const esObj = {
          name: "es6",
          year: 2015,
        };
        Object.freeze(esObg); //冻结对象
        esObj.name = "es2015";
        //成功
        console.log(esObj); //{name:'es6',year:2015}
        
      • 只能做浅层次冻结

      const esObj = {
        name: "es6",
        year: "2015",
        extension: ["es7", "es8", "es9"],
      };
      Object.freeze(esObg);
      esObj.extension[0] = "es2016";
      console.log(esObj); //{name:'es6',year:'2015',extension:['es2016','es8','es9']}
      
    • 封装一个函数,深层冻结

    function myFreeze(obj) {
      Object.freeze(obj);
      Object.keys(obj).forEach(function (key) {
        if (typeof obj[key] === "object") {
          myFreeze(obj[key]);
        }
      });
    }
    
  • 什么时候用 let,什么时候用 const

    • 默认情况下优先使用 const,只有当前的值需要改变的时候才用 let
const sum3 = (x, y) => {
  return x + y;
};
//也可以这样写
const sum4 = (x, y) => x + y;

const sum5 = (x) => x + 1;
  • 箭头函数里面没有 this,它会从上层作用域内找 this
  • 对象里的方法

    const obj = {
      name: "xiecheng",
      showName: function () {
        console.log("我的名字是:" + this.name);
      },
      showName1: () => {
        console.log("我的名字是:" + this.name);
      },
      showName2() {
        //ES对象里面方法的简写形式
        console.log("我的名字是:" + this.name);
      },
    };
    obj.showName(); //我的名字是:xiecheng
    obj.showName1(); //我的名字是:
    obj.showName2(); //我的名字是:xiecheng
    

    箭头函数里的 this 并没有指向对象,而是指向了上一层的 this,在这里是 window

  • 使用 arguments 获取形参

    function sum2(x, y) {
      console.log(arguments);
    }
    sum2(2, 3); //0:2 1:3
    
    const sum3 = (x, y) => {
      console.log(arguments);
      return x + y;
    };
    
    sum3(3, 4); //报错
    

    即箭头函数里不能使用 arguments

  • 定义类

    //类,ES5写法
    function Course(name, price) {
      (this.name = name), (this.price = price);
    }
    
    //类,箭头函数写法
    const Course = (name, price) => {
      this.name = name;
      thia.price = price;
    };
    const c1 = new Course("es", 500);
    console.log(c1); //报错,Course is not a constructor
    
  • 不能定义原型下的方法

    function Course(name, price) {
      (this.name = name), (this.price = price);
    }
    Course.prototype.study = function () {
      //改成箭头函数会报错
      console.log(`我要学习${this.name},价格是${this.price}`); //模板字符串
    };
    const c1 = new Course("es", 500);
    console.log(c1);
    c1.study();
    
const course = {
  name: "es6",
  price: 500,
};
//ES6之前的写法
const name = course.name;
const price = course.price;
console.log(name, price); //es5 500
//ES6的写法
const { name, price } = course; //解构等号左边与右边的对应的结构要完全一样
console.log(name, price); //es5 500

const courseArr = ["es6", "es7", "es8"];
//ES6之前的写法
const a = courseArr[0];
const b = courseArr[1];
const c = courseArr[2];
console.log(a, b, c); //es6 es7 es8
//ES6的写法
const [a, b, c] = courseArr;
console.log(a, b, c); //es6 es7 es8
  • 解构赋值接收值的常量或变量不能重复名字

    const course = {
      name: "es6",
      price: 500,
      teacher: {
        name: "xiecheng",
        age: 34,
      },
    };
    const {
      name,
      price,
      teacher: { name, age },
    } = course;
    console.log(name, price, name, age); //报错,name不能重复定义
    

    可以通过取别名来区分

    const course = {
      name: "es6",
      price: 500,
      teacher: {
        name: "xiecheng",
        age: 34,
      },
    };
    const {
      name: courseName,
      price,
      teacher: { name, age },
    } = course;
    console.log(courseName, price, name, age);
    
  • 把数组作为函数参数

    //之前的写法
    const sum = (arr) => {
      let result = 0;
      for (let i = 0; i < arr.length; i++) {
        result += arr[i];
      }
      return result;
    };
    //ES6的写法
    const sum = ([a, b, c]) => {
      return a + b + c;
    };
    sum([1, 2, 3]);
    
  • 把对象作为函数参数

    const foo = ({ name, age }) => {
      console.log(name, age);
    };
    
    foo({
      name: "张三",
      age: 20,
    });
    
    //设置默认值
    const foo = ({ name, age, school = "XX学校" }) => {
      console.log(name, age);
    };
    
  • 函数返回值为对象

    const foo = () => {
      return {
        name: "张三",
        age: 20,
      };
    };
    const { name, age } = foo();
    console.log(name, age);
    
  • 变量互换

    let a = 1;
    let b = 2;
    [b, a] = [a, b];
    
  • JSON 应用

    const json = '{"name":"es","price":500}';
    const { name, price } = JSON.parse(json);
    
  • 直接对后端返回数据进行解构(Ajax 请求应用)

    axios.get('./data.json').then({data:{name,price}} => {
      console.log(name);
      console.log(price);
    });
    
  • 用 Babel 将 ES6 语法转换成 ES5 语法

    • 安装 Node.js 环境
    • 进入到项目,初始化 package.json
    npm init -y
    
    • 安装
    npm install --save-dev babel-preset-env babel-cli
    
    • 创建文件并配置:.babelrc
    {
      "presets": ["env"]
    }
    
  • 文件转化

    • 文件
    babel src/index.js -o dist/index.js
    
    • 文件夹
    babel src -d dist
    
    • 实时监控
    babel src -w -d dist