Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the use of var that=this in WeChat Mini Programs's development?

Shulou Source: shulou.com Published: 2022-06-03 06:19:13 10月11日 Update

What is the use of var that=this in WeChat Mini Programs's development? I believe many inexperienced people are at a loss about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

In WeChat Mini Programs's development, the declaration of var that = this is common. For example, the code is as follows!

Sample code 1

/ / index.js Page ({data: {toastHidden: true,}, loadData: function () {var that = this//) where that is declared Store this in that wx.request ({url: 'test.php', data: {a:' asides, b:'b'}, header: {'content-type':' application/json'}, success (res) {that.setData ({toastHidden: false}) / / that is used here, so you can get Page ({}) objects},})})

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!

Sample 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})},})})

Running the code at this time will report the following error!

Learn from the error report that the attribute setData can not be read, why not read it? This is related to the scope of the this keyword!

This scope Analysis:

1. In Page ({}), the this keyword refers to the entire object Page ({}).

two。 Therefore, you can access or reset the variable data in Page ({}) through the this keyword.

3. However, the use of wx.request ({}) API in the loadData function makes it impossible to use this to get the Page ({}) object in wx.request ({}).

4. Although you can't use this to get a Page ({}) object in wx.request ({}), you can store this in a variable outside wx.request ({}), so you have the declaration var that = this. At this point, that refers to the whole object of Page ({}), so you can use that in wx.request ({}) to access or reset the variable data in Page ({}).

After reading the above, have you mastered the usage of var that=this in WeChat Mini Programs's development? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Code object small program development key keyword variable method function content more example problem helpless for this example function method reason can be passed through Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Linux Shulou Tech Info MySQL Huawei