微信小程序開發中 var that =this的用法

在微信小程序開發中,var that =this的聲明很常見。舉個例子,代碼以下!php

示例代碼1

1    //index.js
 2   Page({
 3
 4     data: {
 5       toastHidden: true,
 6      },
 7
 8      loadData: function () {
 9        var that = this //這裏聲明瞭that;將this存在that裏面
10        wx.request({
11         url: 'test.php',
12         data: {a: 'a', b: 'b'},
13         header: {
14           'content-type': 'application/json' 
15         },
16         success(res) {
17            that.setData({ toastHidden: false }) //這裏使用了that,這樣就能夠獲取Page({})對象
18        },
19      })
20    }
21
22 })複製代碼

在代碼中第9行聲明瞭var that =this;第17行使用了that。json

若是不聲明var that =this,且that改爲this,代碼以下!小程序

示例代碼2

1    //index.js
 2    Page({
 3
 4      data: {
 5       toastHidden: true,
 6      },
 7
 8      loadData: function () {
 9        wx.request({
10          url: 'test.php',
11          data: {a: 'a', b: 'b'},
12          header: {
13           'content-type': 'application/json' 
14          },
15         success(res) {
16            this.setData({ toastHidden: false })
17         },
18       })
19    }
20
21  })
複製代碼

此時運行代碼就會報如下錯誤!微信小程序

從報錯中得知setData這個屬性讀不到,爲什麼讀不到?這跟this關鍵字的做用域有關!bash

this做用域分析:

1.在Page({})裏面,this關鍵字指代Page({})整個對象微信

2.所以能夠經過this關鍵字訪問或者從新設置Page({})裏data的變量markdown

3.然而在loadData函數中使用了wx.request({})API這個方法致使在wx.request({})裏沒辦法使用this來獲取Page({})對象app

4.雖然在wx.request({})裏無法使用this獲取Page({})對象,可是能夠在wx.request({})外面先把this存在某個變量中,因此就有了 var that =this 這個聲明。此時that指代Page({})整個對象,這樣子就能夠在wx.request({})裏使用that訪問或者從新設置Page({})裏data的變量函數

最後

以爲文章不錯的話,給我個關注哇,點個讚唄!學習

若是對文章有疑問或想技術交流,可關注公衆號【GitWeb】與我一塊兒探索學習!

相關文章
相關標籤/搜索