彻底搞懂var that=this

彻底搞懂var that=this

在此我由衷希望你耐心阅读,并且反复琢磨

彻底理解 var that=this 还是非常有必要的,首先理解这个语句我们要明白 that this 分别是什么。

this:在js中,this用以指代当前对象,但是this随着程序进行,所处环境不同,也是会一直变化的(important)

that:其实单纯只是一个变量名。

既然刚刚说this会变,我们不想让他变怎么办?答: var that=this 将this指向that,这是var that = this 的核心思想。

你以为你懂了???我们带入实例让你彻底明白。

var app = new Vue({
    
    
    el:"#app",
    data:{
    
    
        query:'',
        musicList:[]
    },
    methods:{
    
    
        searchMusic:function(){
    
    
            var that=this;
            axios.get('https://autumnfish.cn/search?keywords='+that.query)
            //注意这里正常人用的都是+this.query
            //1.上面var that = this 此时他们指向是一样的,下面还会具体讲解-->
            .then(function(res){
    
    
                console.log(res)
                that.musicList = res.result.songs
                console.log(that.musicList)
                //2.下面分点讲解
                console.log(this.musiclist)
                //3.
            }),function(){
    
    
                console.log(err)
            }

        }
        
    }
})

在这里插入图片描述

  1. axios.get(‘https://autumnfish.cn/search?keywords=’+that.query) 这里我专门换成 that 没有使用 this ,之前的this指向是挂载的app,所以在var that = this 之后,that.query与this.query 是一样的。
  2. 这里是console.log(that.musiclist) 输出的结果,that相当于之前this指向挂载的app,也相当与存储了之前的this,所以这里是可以打印出来的。
  3. 这时候我们发现找不到 this 所指的对象了,之前说过this会发生变化,在这里this 就是指向的函数的回调,不是之前挂载的app, 所以在这一层是找不到musiclist的。 换一个角度解释,this代表父函数,如果在子函数还用this,this的指向就变成子函数,that是用来存储指向的。

如果这篇文章对你有所帮助请关注公众号,更多精彩内容等着你!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46145739/article/details/113783353