箭头函数中的this

  JavaScript的函数(函数声明式)中,this指向的是运行时的作用域,如果没有对象调用函数,则this指向 global/window,但是在箭头函数中,this的指向是固化的,如下面代码所示:

 1 function Timer() {
 2     this.s1 = 0
 3     this.s2 = 0
 4     setInterval(() => {
 5         this.s1++
 6     }, 1000)
 7     setInterval(function () {
 8         // console.log(this)
 9         this.s2++
10     }, 1000)
11 }
12 
13 var timer = new Timer()
14 
15 setTimeout(() => console.log('s1: ', timer.s1), 3100) // 3
16 setTimeout(() => console.log('s1: ', timer.s2), 3100) // 0

  那么怎样理解输出的结果呢?其实只需要搞清楚在第4行和第7行中两个函数this的指向就行了。

  在第4行中,使用的是箭头函数,箭头函数this绑定定义时所在的作用域(即Timer函数),则该this指向的是Timer函数中的对象

  在第7行中,使用的是函数声明式,此时this指向运行时的作用域,即全局对象,操作的自然就不是Timer函数中的s2了

 1 function Timer() {
 2     this.s1 = 0
 3     this.s2 = 0
 4     setInterval(() => {
 5         this.s1++
 6     }, 1000)
 7     setInterval(func.bind(this), 1000)
 8     function func() {
 9         this.s2++
10     }
11 }
12 
13 var timer = new Timer()
14 
15 setTimeout(() => console.log('s1: ', timer.s1), 3100) // 3
16 setTimeout(() => console.log('s1: ', timer.s2), 3100) // 3

  改代码是上面代码的更改版,在第7行中,func还是函数声明式,但是对该函数的this使用了bind进行了绑定,所以该函数的作用域从全局作用域更改成为了Timer函数作用域

总结:

  1. 箭头函数可以让this指向固化,但是this指向固化并不是因为箭头函数内部有绑定的this机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。(使用作用链域思想理解)正是由于箭头函数没有this,所以不能用作构造函数。

  2. arguments、super和new.target在箭头函数中是不存在(可以使用,只不过这三个变量的作用域指向的是外层函数)

  3. 由于箭头函数中没有自己的this,所以箭头函数不能使用call(),apply(),bind()这三个方法去改变this的指向。

引用地址:

  1. 《ES6标准入门》,118页~121页。

  2.  一篇写JS函数(声明式)的this的博客,写的非常棒:https://www.cnblogs.com/xiangxiao/p/6822997.html 

原文地址:https://www.cnblogs.com/oulae/p/11072265.html