美文网首页
箭头函数

箭头函数

作者: me_coder | 来源:发表于2019-12-10 11:07 被阅读0次

    箭头函数没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以也就不能用作构造函数。
    一个示例:

    // ES6
    function foo() {
      setTimeout(() => {
        console.log('id:', this.id);
      }, 100);
    }
    
    // ES5
    function foo() {
      var _this = this;
    
      setTimeout(function () {
        console.log('id:', _this.id);
      }, 100);
    }
    

    除了没有this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:argumentssupernew.target
    另外,由于箭头函数没有自己的this,所以当然也就不能用call()apply()bind()这些方法去改变this的指向。

    (function() {
      return [
        (() => this.x).bind({ x: 'inner' })()
      ];
    }).call({ x: 'outer' });
    // ['outer']
    

    不适用的场合

    1、定义对象的方法,且该方法内部包括this

    const cat = {
      lives: 9,
      jumps: () => {
        this.lives--;
      }
    }
    

    此时,this指向全局对象,而不使用箭头函数的时候this指向cat对象。
    2、需要动态this的时候

    var button = document.getElementById('press');
    button.addEventListener('click', () => {
      this.classList.toggle('on');
    });
    

    这个this也指向全局对象,而普通函数则指向被点击的按钮。

    相关文章

      网友评论

          本文标题:箭头函数

          本文链接:https://www.haomeiwen.com/subject/spgwgctx.html