javascript中promise中this关键字


  本例是在VUE + ELEMENT-UI的环境中,在javascrpit的promise中调用完接口,在then中要调用element-ui的消息提示框.刚开始是这样写的:

onSubmit() {
      instance
        .post(
          `http://localhost:8989/user/regist/${this.verifyCode}/${this.key}`,
          this.user
        )
        .then(function(response){   
          console.log(this);      
          if (response.data.code === 200) {
            this.$alert("点击跳转到登录页面", "注册成功", {
              confirmButtonText: "确定",
              callback: action => {
                this.$message({
                  type: "info",
                  message: `action: ${action}`
                });
              }
            });
          } else {
            this.$message({
              message: response.data.msg,
              type: "error"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
          this.$message.error(error);
        });
    },

  这样在红色代码处的this是undefined.

  但是将代码中绿色代码中的函数定义换成箭头函数,红色代码处就可以访问this了,而且这个this就是,顶层的VUE对象.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM