前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JS回调函数中的 this 指向(详细)

JS回调函数中的 this 指向(详细)

作者头像
TimothyJia
发布2019-11-12 14:26:53
7.2K0
发布2019-11-12 14:26:53
举报

首先先说下正常的 this 指向问题

什么是 this:自动引用正在调用当前方法的.前的对象。

this指向的三种情况

1. obj.fun() fun 中的 this->obj ,自动指向.前的对象

2. new Fun() Fun 中的 this->正在创建的新对象,new 改变了函数内部的 this 指向,导致 this 指向实例化 new 的对象

3. fun() 和匿名函数自调 this 默认->window,函数内部的 this,this 默认是指向 window 的

再说回调函数中的 this 指向问题,我们先来看一个例子

代码语言:javascript
复制
 1 <script>
 2     var Bob={
 3         sname:"鲍勃",
 4         friends:["Jack","Rose","Tom","Jerry"],
 5         intr(){
 6           this.friends.forEach(function(ele){
 7                console.log(this.sname+"认识"+ele);
 8           });
 9         }
10     }
11     Bob.intr();
12 </script>    

看结果:

undefined认识Jack undefined认识Rose undefined认识Tom undefined认识Jerry

回调函数中的this默认是指向window的,因为本质上是在函数内callback,并没有.前的对象调用

如何解决:

使用箭头函数

代码语言:javascript
复制
 1<script>
 2     var Bob={
 3         sname:"鲍勃",
 4         friends:["Jack","Rose","Tom","Jerry"],
 5         intr(){
 6           this.friends.forEach(ele=>{
 7                console.log(this.sname+"认识"+ele);
 8           });
 9         }
10     }
11     Bob.intr();
12 </script>  

结果是:

鲍勃认识Jack 鲍勃认识Rose 鲍勃认识Tom 鲍勃认识Jerry

可以看出箭头函数内的this自动指向了回调函数外层的 this 。

箭头函数中的 this:

  函数体内的 this 对象,就是定义时所在的对象,而不是使用时所在的对象。

  this 指向的固定化,并不是因为箭头函数内部有绑定 this 的机制,实际原因是箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。正是因为它没有 this,所以也就不能用作构造函数。

也可使用bind永久绑定this

代码语言:javascript
复制
 1 var Bob={
 2         sname:"鲍勃",
 3         friends:["Jack","Rose","Tom","Jerry"],
 4         intr(){
 5           this.friends.forEach(function(friend){
 6                console.log(this.sname+"认识"+friend);
 7           }.bind(this));
 8         }
 9     }
10     Bob.intr();  
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档