ES6箭头函数

118 阅读1分钟

箭头函数特点

  • 如果参数只有一个,可以省略小括号;
  • 如果函数体只有一行,可以不写大括号;
  • 箭头函数没有arguments变量;
  • 不会改变this指向

箭头函数没有自己的this,导致内部this就是外层代码块的this

函数体只有一行不写大括号

let getTempItem = id =>({id:id,name:'temo'})
console.log(getTempItem(20))

this指向

  • 普通函数this是在使用的时候确定的,指向调用者
  • 箭头函数this指向外层函数的this
// 普通函数
var person = {
name:'Evan',
age:18,
func:function(){
    console.log(this)
    }
}
person.func() // this指向person对象

// 箭头函数 编写对象不推荐此种写法
var person = {
name:'Evan',
age:18,
func:()=>{
    console.log(this)
    }
}
person.func() //this 指向window对象

严格模式下this指向undefined

function f2(){
  "use strict"; // 这里是严格模式
  return this;
}

f2() === undefined; // true

setTimeout & setInterval 中this

var id = 21;
function foo(){
    setTimeout(function(){
        console.log('id:',this.is);
    },1000)
}
foo.call({id:52});// id:21 内部不能通过call,bind this改变
foo(); // id:21

function foo2(){
    setTimeout(()=>{
        console.log('id:',this.is);
    },1000)
}
foo2.call({id:42});// id:42