小程序模板網(wǎng)

微信小程序開發(fā)中 var that =this的用法

發(fā)布時間:2020-05-22 09:59 所屬欄目:小程序開發(fā)教程

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

示例代碼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。

如果不聲明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  })

此時運(yùn)行代碼就會報以下錯誤!

從報錯中得知setData這個屬性讀不到,為何讀不到?這跟this關(guān)鍵字的作用域有關(guān)!

this作用域分析:

1.在Page({})里面,this關(guān)鍵字指代Page({})整個對象

2.因此可以通過this關(guān)鍵字訪問或者重新設(shè)置Page({})里data的變量

3.然而在loadData函數(shù)中使用了wx.request({})API這個方法導(dǎo)致在wx.request({})里沒辦法使用this來獲取Page({})對象

4.雖然在wx.request({})里沒法使用this獲取Page({})對象,但是可以在wx.request({})外面先把this存在某個變量中,所以就有了var that =this 這個聲明。此時that指代Page({})整個對象,這樣子就可以在wx.request({})里使用that訪問或者重新設(shè)置Page({})里data的變量


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.u-renovate.com/wxmini/doc/course/25256.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢
AI智能客服 ×