A detailed explanation of the usage of VaR that = this in the development of wechat applet

Time:2020-3-28

In wechat applet development, the declaration of VaR that = this is very common. For example, the code is as follows!

Example code 1

//index.js 
 Page({ 
  
  data: { 
  toastHidden: true, 
  }, 
  
  loadData: function () { 
   Var that = this // that is declared here; this is stored in that 
   wx.request({ 
    url: 'test.php', 
    data: {a: 'a', b: 'b'}, 
    header: { 
    'content-type': 'application/json' 
    }, 
    success(res) { 
      That. SetData ({toasthidden: false}) // that is used here to get the page ({}) object 
    }, 
   }) 
  } 
 
 })

In the code, line 9 declares var that = this; line 17 uses that.

If var that = this is not declared, and that is changed to this, the code is as follows!

Example code 2


 //index.js 
  Page({ 
 
  data: { 
   toastHidden: true, 
  }, 
 
  loadData: function () { 
   wx.request({ 
   url: 'test.php', 
   data: {a: 'a', b: 'b'}, 
   header: { 
    'content-type': 'application/json' 
   }, 
   success(res) { 
    this.setData({ toastHidden: false }) 
    }, 
   }) 
  } 
 
 })

At this time, the running code will report the following error!

We know from the error report that SetData cannot be read. Why can’t we read it? This is related to the scope of this keyword!

This scope analysis:

1. In page ({}), this keyword refers to the whole page ({}) object

2. Therefore, you can access or reset the data variables in page ({}) through this keyword

3. However, the Wx. Request ({}) API is used in the loaddata function, which makes it impossible to use this to get the page ({}) object in Wx. Request ({})

4. Although this cannot be used to get the page ({}) object in Wx. Request ({}), you can first put this in a variable outside Wx. Request ({}), so there is the declaration of VaR that = this. In this case, that refers to the whole object of page ({}), so that the child can use that in wx.request ({}) to access or reset the variables of data in page ({})

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.