微信小程序ES6——箭頭函數中的this問題


背景

  •  在開發微信小程序過程中,在一個回調函數中對js中的變量賦值時出現報錯:Cannot read property 'setData' of undefined;at api chooseImage success callback function
  • 代碼如下
    wx.chooseImage({
          count: 3,
          sizeType: ['original'],
          sourceType: ['album', 'camera'],
          success (res) {
            // tempFilePath可以作為img標簽的src屬性顯示圖片
            const tempFilePaths = res.tempFilePaths;
            this.setData({
              imgPaths:tempFilePaths
            });
          },
          fail(err){
    
          }
        });
      },
  • 錯誤如下
    VM6263:1 thirdScriptError
    Cannot read property 'setData' of undefined;at api chooseImage success callback function
    TypeError: Cannot read property 'setData' of undefined
        at success (http://127.0.0.1:43580/appservice/pages/comment/comment.js:42:14)
        at Function.o.<computed> (WAService.js:1:1116874)
        at Object.success (WAService.js:1:102889)
        at r (WAService.js:1:418891)
        at WAService.js:1:419068
        at v (WAService.js:1:419077)
        at WAService.js:1:420485
        at t.<anonymous> (http://127.0.0.1:43580/appservice/__dev__/asdebug.js:1:10431)
        at WAService.js:1:102889
        at WAService.js:1:90451
  • Next

錯誤原因

  • 普通函數中,this的概念是:this是JavaScript的一個關鍵字,他是指函數執行過程中,自動生成的一個內部對象,是指當前的對象,只在當前函數內部使用。(this對象是在運行時基於函數的執行環境綁定的:在全局函數中,this指向的是window;當函數被作為某個對象的方法調用時,this就等於那個對象)
  • 回調函數中使用的this關鍵字,是在回調函數創建過程中再次生成的一個對象,並不是指向一個全局對象,所以報錯找不到相應的屬性或者方法。

普通函數中和ES6箭頭函數中this的區別

  • 普通函數
    • 定義:普通函數的this是指函數執行過程中,自動生成的一個內部對象,是指當前的對象,只在當前函數內部使用回調函數中,當函數被作為某個對象的方法調用時,this就等於那個對象
    • 解釋:每次在執行一個函數的過程中,每一個函數都會生成一個相對應的this對象。這些this對象不同。
  • ES6箭頭函數
    • 定義:箭頭函數的this是在定義函數時綁定的,不是在執行過程中綁定的。簡單的說,函數在定義時,this就繼承了定義函數的對象
    • 解釋:箭頭函數中定義的this,會自動繼承全局this。
  • Next

舉例

  • 普通函數,回調函數中this的使用
    • 代碼如下
      //上傳圖片
        uploadImg:function(event){
          //1.選擇圖片
          var _this=this;  //如果想要在下面的success回調函數中使用全局this對象,這里需要進行變量轉換。
          wx.chooseImage({
            count: 3,
            sizeType: ['original'],
            sourceType: ['album', 'camera'],
            success (res) { const tempFilePaths = res.tempFilePaths; _this.setData({ imgPaths:tempFilePaths }); },
            fail(err){
      
            }
          });
        },
    • Next
  • ES6箭頭函數,回調函數中this的使用
    • 代碼如下
      //上傳圖片
        uploadImg:function(event){
          //1.選擇圖片
          // var _this=this;
          wx.chooseImage({
            count: 3,
            sizeType: ['original'],
            sourceType: ['album', 'camera'],
            success :res=> { //如果使用箭頭函數,回調函數內就可以直接使用this對象,因為this已經繼承了uploadImg的全局this對象 const tempFilePaths = res.tempFilePaths; this.setData({ imgPaths:tempFilePaths }); }, fail:err=>{ }
          });
        },
    • Next
  • Next


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM