ES6总结 第五节 箭头函数this的指向和注意事项

207 阅读1分钟

es5函数中使用this与es中箭头函数中使用this的不同

1. es5中的this指向

let pageHandle = {
    id: 123,
    handle: function(){
        console.log(this) // {id: 123, handle: ƒ}
        console.log(this.id) //123
        document.addEventListener('click', function(){
        	//因为该匿名函数被ducument调用,指向的是document对象
            console.log(this)  //点击页面后会输出 doucument对象
        })
    }
}
pageHandle.handle()

2. es6箭头函数中的this指向


let pageHandle = {
    id: 123,
    handle: function(){
        console.log(this.id) //123
        document.addEventListener('click', ()=>{
        	//箭头函数没有this指向,箭头函数的内部this指只能通过查找作用域来确定,一旦使用箭头函数,当前就不存在作用域链
            console.log(this) // {id: 123, handle: ƒ}
        })
    }
}
pageHandle.handle()

箭头函数使用的连个注意事项

1. 箭头函数中不能使用arguments参数

//箭头函数
let func = (a, b)=>{
    console.log(arguments)  //报错
}
func(1,2)

//es5 函数
function func(a, b){
    console.log(arguments)  //正常输出结果
}
func(1,2)

2. 箭头函数不能实例化对象

// 箭头函数实例化对象
let Person = name => {
}
let person = new Person() //Error Person is not a constructor
// es5函数示例化对象
let Person = function(name){
    this.name = name
}
let person = new Person('Tom')
console.log(person.name)  // Tom