• ES6知识整理(一)--- let/const/箭头函数


    转自:https://blog.csdn.net/Creabine/article/details/79016811

    早在17年初就读了《ES6 标准入门》并在博客上做了笔记(《ES6 标准入门》读书笔记),工作中也有用到一些。一年后再回过头来看这些知识,又跟初看的时候的感觉完全不同了。对很多新特性的好处有了更具体的认识。也有一些知识依然了解不够,所以在这里重新整理一波,夯实基础。

    箭头函数

    箭头函数主要有两个好处: 
    1. 减少代码量 
    2. 绑定函数定义时的作用域 
    对于1,这里记录一个比较刁钻的小例子:

    let multiply = (a, b) => b === undefined ? b => a * b : a * b;
    let double = multiply(2);
    double(3); // => 6  
    multiply(2, 3); // => 6
    // 也就是
    function multiply(a, b) {
        if (b === undefined) {
            return function(b) {
                return a * b;
            }
        }
        return a * b;
    }
    let double = multiply(2);
    double(3); // => 6  
    multiply(2, 3); // => 6
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    对于2的使用比较普遍,尤其是在一些会改变作用域的地方。比较常见的例子是setInterval,我们知道setInterval中的this指向的是window对象。如果不使用箭头函数,我们要这样写:

    // 给this赋值
    let obj = {
      time: 3,
      count () {
        let self = this
        console.log(this.time)
        this.interval = setInterval(function () {
          console.log(self.time);
        }, 1000)
      }
    }
    obj.count()
    // 使用bind方法
    let obj = {
       time: 3,
       count () {
         console.log(this.time)
         this.interval = setInterval(function () {
           console.log(this.time);
         }.bind(this), 1000)
       }
     }
     obj.count()
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    可以说是很麻烦了,但是如果使用箭头函数,会自动绑定函数声明时的作用域。完全不用理会这个问题:

    let obj = {
      time: 3,
      count () {
        console.log(this.time)
        this.interval = setInterval(() => {
          console.log(this.time)
        }, 1000)
      }
    }
    obj.count()
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    let/const关键字

    使用let/const定义变量之后,就可以完全代替var了。 
    let/const没有变量提升,所以一定要先声明后使用。 
    let/const为js增加了块级作用域,例如:

    function f1() {
        let n = 5;
        if (true) {
            let n = 10;
        }
        console.log(n); // 5
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    const声明一个只读常量,一旦声明要立即初始化。const声明的对象,只是对象的地址不变,对象本身是可变的。const声明的数组可以使用数组的方法但无法重新赋值。 
    从ES6开始,全局变量将逐步与全局对象的属性脱钩。let,const,class声明的全局变量,不再属于全局对象的属性,例如:

    var a = 1
    window.a // 1
    let b = 1;
    window.b // undefined
  • 相关阅读:
    【BZOJ 4151 The Cave】
    【POJ 3080 Blue Jeans】
    【ZBH选讲·树变环】
    【ZBH选讲·拍照】
    【ZBH选讲·模数和】
    【CF Edu 28 C. Four Segments】
    【CF Edu 28 A. Curriculum Vitae】
    【CF Edu 28 B. Math Show】
    【CF Round 439 E. The Untended Antiquity】
    【CF Round 439 C. The Intriguing Obsession】
  • 原文地址:https://www.cnblogs.com/chinet/p/9285876.html
Copyright © 2020-2023  润新知