es6箭头函数

箭头函数需要注意的几个点

1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象(这一点非常重要)

箭头函数内部没有this,而是引用外部的this

function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

var id = 21;
foo()  //this指向函数定义时所在的对象,也就是foo,输出21
foo.call({ id: 42 });   //this指向函数定义时所在的对象,也就是{id:42},输出42

function bar() { 
  setTimeout(function() {
    console.log('id:', this.id);
  }, 100);
}

var id = 21;
bar() //对于非箭头函数,this指向全局window,输出21
bar.call({ id: 42 }); //对于非箭头函数,this指向全局window,输出21

箭头函数可以让函数中的this绑定定义时所在的作用域,而不是运行时所在的作用域

        function Timer() {
            this.s1 = 0;
            this.s2 = 0;
            // 箭头函数
            setInterval(() => this.s1++, 1000);
            // 普通函数
            setInterval(function () {
                this.s2++;
            }, 1000);
        }

        var timer = new Timer();

        setTimeout(() => console.log('s1: ', timer.s1), 3100); //3
        setTimeout(() => console.log('s2: ', timer.s2), 3100);  //0

箭头函数中的this指向timer,而普通函数中的this指向全局,所以s1为3,而s2并没有发生改变

不适用场合

var v = "000"
var obj1 = {
    v:111,
    foo:function(){
        console.log(this.v)
    }
}
obj1.foo() //this指向obj1
var obj2 = {
    v:222,
    foo:()=>{
        console.log(this.v)
    }
}
obj2.foo() //this指向全局

 需要动态this时,不应该使用箭头函数

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

  

2)不可以当作构造函数,也就是不可以new命令,否则报错

3)不可以使用argments对象,该对象在函数体内不存在,如果需要,可以使用rest参数代替

4)不可以使用yield命令,箭头函数不能作Generator函数

原文地址:https://www.cnblogs.com/lhyhappy365/p/10308073.html