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