一 箭头函数中的 this
对于 ES5 中普通函数来说,this 会绑定到函数执行时的上下文,比如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
var o={ arr:[1,2,3] loop:this.arr.forEach(function(v){ console.log(this.arr) // undefined,这里this为window,浏览器里forEach中的函数执行时,context为window }) }
//所以如果想让this指向对象o,需要进行绑定 var o={ arr:[1,2,3], loop:this.arr.forEach(function(v){ console.log(this.arr) // undefined,这里this为window,浏览器里forEach中的函数由window执行 }.bind(this)) }
|
而在 ES6 的箭头函数中,this 不会绑定到执行时的上下文,箭头函数的 this 为词法绑定,就是绑定到函数定义时的上下文,即 this 来自于包含箭头函数的代码块中的定义
1 2 3 4 5 6
|
var o={ arr:[1,2,3], loop:this.arr.forEach((v)=>{ console.log(this.arr) // 这里this就是o }) }
|
二 适用/不适用场景
适用
this 固定为定义时的 context,不随执行变化
不适用
1.直接用在对象方法上
1 2 3 4 5 6
|
var o = { name: 9, fn: () => { console.log(this.name) //undefined,此时this==window } }
|
2.context 随执行变化的场景
1 2 3 4
|
var button = document.getElementById('press'); button.addEventListener('click', () => { this.classList.toggle('on'); // 这里this无法指向button元素,而是指向了window });
|