关于ES6的箭头函数
话不多说,首先来看一段代码
var j = 9
console.log(j) //9
console.log(global.j) //undefined
global.j = 11
console.log(global.j) //11
function Outer() {
var fun = () => {
console.log(this.j) //8
}
fun()
function fun1(){
console.log(this.j) //11
}
fun1()
this.j = 10
// let j=10
var foo = () => {
console.log(this.j) //10
// console.log(this)
}
foo()
var fun2 = function () {
console.log(this.j) //10
}
fun2()
setTimeout(function fun3() {
let j = 12
console.log(this.j) //undefined
}, 0)
}
const my = {
j: 8
}
console.log(my.j) //8
Outer.call(my)
console.log(my.j) //10
Outer()// 依次输出11 11 10 10 undefined
首先var声明的变量和global变量已经不再有关联,这个由Outer()函数上的几个输
出就可以看出来,建议可以复制上面一段代码到编译器运行一下。
之后我们来探讨一下箭头函数的this问题,在ES6入门中,阮老师说到,箭头函数
的this绑定在函数定义生效的时候,那么什么时候箭头函数定义生效呢,在此例中,就是Outer()函数执行的时候。
所以当分别以global和my调用Outer()时,j的值均不相同。
当用my调用Outer()的时候,箭头函数输出的是调用者的this.j,输出8,而普通函数由global调用,输出11,当this.j在函数Outer()中改变的时候,箭头函数随着改变,但是普通函数fun2依然输出11,可见this.j改变的是my的this.j。为什么这么说?请看第二次直接在全局中执行Outer()的输出。
此时Outer()由global调用,箭头函数和普通函数fun1的执行结果相同,而当this.j 改变的时候,箭头函数输出的j改变了,同样普通函数fun3也改变,他们都是跟着global的this走。
个人体会,仅供参考。大家可以自己动手试一试,验证自己的想法。