zoukankan      html  css  js  c++  java
  • 箭头函数

    引入箭头函数有两个方面的作用:更简短的函数并且不绑定this;

    1、更简短的函数

    var materials = [
      'Hydrogen',
      'Helium',
      'Lithium',
      'Beryllium'
    ];
    
    materials.map(function(material) { 
      return material.length; 
    }); // [8, 6, 7, 9]
    
    materials.map((material) => {
      return material.length;
    }); // [8, 6, 7, 9]
    
    materials.map(material => material.length); // [8, 6, 7, 9]

      箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }return

    // 可变参数:
    (x, y, ...rest) => {
        var i, sum = x + y;
        for (i=0; i<rest.length; i++) {
            sum += rest[i];
        }
        return sum;
    }

      如果要返回一个对象,就要注意,如果是单表达式,这么写的话会报错:

    // SyntaxError:
    x => { foo: x }

      因为和函数体的{ ... }有语法冲突,所以要改为:

    // ok:
    x => ({ foo: x })

    2、不绑定this

      在箭头函数出现之前,每个新定义的函数都有它自己的 this值(在构造函数的情况下是一个新对象,在严格模式的函数调用中为 undefined,如果该函数被称为“对象方法”则为基础对象等。

      例1️⃣

    function Person() {
      // The Person() constructor defines `this` as an instance of itself.
      this.age = 0;
      console.log(this);    //Person {age: 0}
    
      setInterval(function growUp() {
        // In non-strict mode, the growUp() function defines `this` 
        // as the global object, which is different from the `this`
        // defined by the Person() constructor.
        console.log(this) //window
       console.log(this.age) //undefined
    this.age++; }, 1000); } var p = new Person();

      在ECMAScript 3/5中,通过将this值分配给封闭的变量,可以解决this问题。

    function Person() {
      var that = this;
      that.age = 0;
      console.log(this,11);//Person{age:0}
    
      setInterval(function growUp() {
        // The callback refers to the `that` variable of which
        // the value is the expected object.
        console.log(that.age);
        that.age++;
      }, 1000);
    }
    var p = new Person();

      箭头功能不会创建自己的this;它使用封闭执行上下文的this值。因此,在下面的代码中,传递给setInterval的函数内的this与封闭函数中的this值相同:

    function Person(){
      this.age = 0;
    
      setInterval(() => {
        this.age++; // |this| properly refers to the person object
      }, 1000);
    }
    
    var p = new Person();

      综上:在普通函数中,this指向window;在构造函数中,this指向new的实例;在setinterval中,this指向window,而此时箭头函数中,this指向封闭函数中的this。

    3、箭头函数的其他适用环境

    // An empty arrow function returns undefined
    let empty = () => {};
    
    (() => 'foobar')(); 
    // Returns "foobar"
    // (this is an Immediately Invoked Function Expression 
    // see 'IIFE' in glossary)
    
    var simple = a => a > 15 ? 15 : a; 
    simple(16); // 15
    simple(10); // 10
    
    let max = (a, b) => a > b ? a : b;
    
    // Easy array filtering, mapping, ...
    
    var arr = [5, 6, 13, 0, 1, 18, 23];
    
    var sum = arr.reduce((a, b) => a + b);  
    // 66
    
    var even = arr.filter(v => v % 2 == 0); 
    // [6, 0, 18]
    
    var double = arr.map(v => v * 2);       
    // [10, 12, 26, 0, 2, 36, 46]
    
    // More concise promise chains
    promise.then(a => {
      // ...
    }).then(b => {
      // ...
    });
    
    // Parameterless arrow functions that are visually easier to parse
    setTimeout( () => {
      console.log('I happen sooner');
      setTimeout( () => {
        // deeper code
        console.log('I happen later');
      }, 1);
    }, 1);

     推荐相关文章:

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    https://juejin.im/entry/584fa735128fe100692e9f02                  https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001438565969057627e5435793645b7acaee3b6869d1374000

  • 相关阅读:
    MySQL主从复制与读写分离
    使用PHPCMS搭建wap手机网站
    phpcms v9不用下插件自己做留言板
    css关于banner图轮播的实现
    MySql和Oracle的日期转换到底有哪些不同?我们来比较一下
    CSS---解决内容过多就会出文本溢出(显示在区域外面,不换行的情况)
    dedecms 后台发布后的文章不能编辑出现一片空白的解决办法
    python常识系列11-->python发送邮件基础
    python常识系列10-->python代码注释规范
    python常识系列09-->logging模块之handlers的使用
  • 原文地址:https://www.cnblogs.com/xiaoli52qd/p/7891229.html
Copyright © 2011-2022 走看看