es6中的arrowfunction

es6新增箭头函数,主要解决了如下几点问题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是离他最近的做用域链的thisui

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

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

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

没有arguments。spa

相关文章
相关标签/搜索