先说结论:
- 箭头函数this指向:
- 箭头函数没有this指向,箭头函数内部的this只能通过查找作用域链来确定
- 箭头函数使用注意事项:
- 使用箭头函数,函数内部没有arguments
- 箭头函数不能使用new 关键字来实例化对象。
箭头函数this指向 例子:
let pageHandle = {
id:123,
init:function(){
document.addEventListener('click',function(){
console.log(this)
this.do(event.type)
},false)
},
do:function(type){
console.log(`点击事件类型:${type},当前id:${this.id}`)
}
}
pageHandle.init()
打印结果: #document
报错信息:
es6.html:14 Uncaught TypeError: this.do is not a function
at HTMLDocument.<anonymous> (es6.html:14)
我们看到里面打印的this是document,所以下边打印this.do(event.type)就会报错。我们可以这样修改
let pageHandle = {
id:123,
init:function(){
document.addEventListener('click',(event)=>{
console.log(this)
this.do(event.type)
},false)
},
do:function(type){
console.log(`点击事件类型:${type},当前id:${this.id}`)
}
}
pageHandle.init()
打印结果:
{id: 123, init: ƒ, do: ƒ}
点击事件类型:click,当前id:123
因为箭头函数没有this指向,所以this的值要向上一层作用域链
箭头函数使用注意事项 例子:
1.箭头函数内部没有arguments
let getVal = (a,b) => {
console.log(arguments)
return a + b
}
console.log(getVal(1,3))
运行结果:报错
Uncaught ReferenceError: arguments is not defined
at getVal (es6.html:24)
at es6.html:27
2.箭头函数不能使用new关键字实例化对象
let person = ()=>{
}
//注:function函数也是一个对象,但是箭头函数不是一个函数,他其实是一个语法糖
let p = new Person()