ajax使用this失效

我们使用ajax的时候,会发现在ajax,success和error方法里面使用this有问题,这是因为ajax里使用的this是指的ajax本身这个对象了,并不是ajax外面的对象。解决方法有2种,如果项目不考虑浏览器兼容的话,推荐是同es6箭头函数,方便很多,注意ide的js版本设置
(1)定义新的变量保存外边的this,
var _this = this;
$.ajax({
    url: '/demo/user/login',
    type: 'post',
    data: {'username':this.username,'password':this.password},
    dataType: 'json',
    success: function (res) {
        if (res.code == 0) {
            location.href = './index.html';
        } else {
            _this.$message({
                message: res.msg,
                type: 'warning'
            });
        }
    },
    error: function (res) {
        _this.$message.error('操作失败');
    }
});

(2)使用es6箭头函数

$.ajax({
    url: '/demo/user/login',
    type: 'post',
    data: {'username':this.username,'password':this.password},
    dataType: 'json',
    success: (res) => {
        if (res.code == 0) {
            location.href = './index.html';
        } else {
            this.$message({
                message: res.msg,
                type: 'warning'
            });
        }
    },
    error: (res) => {
        this.$message.error('操作失败');
    }
});

至于为什么箭头函数能解决这个问题,以下这段话网上找的,并非原创1. 在箭头函数出现之前,每个新定义的函数都有其自己的this值(例如,构造函数的 this 指向了一个新的对象;严格模式下的函数的 this 值为 undefined;如果函数是作为对象的方法被调用的,则其 this 指向了那个调用它的对象)。
2. 箭头函数没有自己的this,不会新产生自己作用域下的this,箭头函数里面的this指向它外层的环境里的this,它没有自己的this。arguments,super和new.target等对象。此外,箭头函数总是匿名的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值