为什么同是promise 在then方法中的this指向不同呢?

Vue中axios请求使用时候,比如要用bind(this)或者var _this = this才能获取VueComponent对象
比如:

var _this = this;

axios("/brandInfo/deleteBrandInfo", _this.param({
                brandId: _this.data[_this.deleteIndex].id,
            })).then(function (res) {
                if (res.data.code == 1) {
                    _this.pullBrandRoute();
                } else {
                    throw res.data.message;
                }
            }).catch(function (err) {
                _this.$Message.error(err);
            });
            

我以为是promise的问题,于是自己写了一个promise

function p(type){
            return new Promise((resolve,reject)=>{
                if (type=='yes') {
                    setTimeout(()=>{
                        resolve('resolved');
                    },5000);
                }else{
                    setTimeout(()=>{
                        reject('rejected');
                    },5000);
                }
            })
        }
        function resolve(){
            console.log('before:',this)
            p('yes').then(res=>{
                console.log('res',this);
                console.log(res);
            }).catch(err=>{
                console.log('err',this);
                console.log(err);
            })
        }
        

打印出来的this都是指向了window
为什么同是promise 在then方法中的this指向不同呢?

阅读 7.9k
2 个回答

JavaScript 里普通函数(通过 function 定义)中的 this 是动态绑定的,也就是说它不看你如何定义,而是看如何使用。

像你最后的例子中,相信你是直接 resolve() 调用,那么非严格模式下这个函数里面的 this 就是 window。后面的两个 this 因为是在箭头函数里,所以直接跳过箭头函数用了上一层 resolve 里的 this,也同样是 window

如果你通过 resolve.call(p) 调用,那么可以观察到三个 this 也会指向 p

推荐阅读这篇文章《JavaScript this 的六道坎》了解 this 的几种变化。

看起来似乎是箭头函数和 functionthis 指向问题,参考 箭头函数 MDN

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题