es6中的arrowfunction

es6新增箭头函数,主要解决了以下几点问题

  1. 函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
  2. 不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
  3. 不可以使用arguments对象,该对象在函数体内不存在。
    var obj = {
    a:1,
    b:2,
    c:function(){
    setTimeout(()=>{
    console.log(this);
    },1000)
    },
    d:function(){
    setTimeout(function(){
    console.log(this)
    },1000)
    }
    }
    obj.c();//obj
    obj.d();//window

setTimeout的this为window,所以d()会输出window,而使用箭头函数则会输出obj

var obj = {
a:function(){
console.log(this)
},
b:()=>{
console.log(this);
}
}
obj.a()//obj
obj.b()//window

可见箭头函数里面的this是离他最近的作用域链的this

var x = new obj.a();
var y = new obj.b();//报错

可见箭头函数不能使用new命令。

var obj = {
a:function(){
console.log(arguments)
},
b:()=>{
console.log(arguments);
}
}
obj.a()
obj.b()//arguments is not defined

没有arguments。

原文地址:https://www.cnblogs.com/newze/p/7535474.html