JavaScript的匿名函数中this指向window

在自己练习Vue实现效果时,在methods中使用了()=>{}这样的lambda表达式函数。

audioPlay: () => {
   this.posterRotate = true;
}

此处原来是根据posterRotate的值修改一个class,但是无论怎么样都触发不到,后来尝试输出this的值,发现this是指向window的。

Window https://localhost:44315/musicPlayer.html

至此,发现this的指向不是Vue实例中,因此修改的posterRotate并不是想修改的那个posterRotate,代码修改为:

audioPlay: function () {
   this.posterRotate = true;
}

正常运行代码,特此记录,Vue实例中需要使用this时未免麻烦不要使用匿名函数的方式。

之后上网查了下,javascript中函数的this指向函数的最后调用者,而匿名函数在非严格版中默认调用者是window。

posted @ 2021-01-12 15:50  lionjian  阅读(533)  评论(0)    收藏  举报