All Products
Search
Document Center

Mobile Platform as a Service:getApp method

Last Updated:Feb 02, 2021

The mPaaS framework provides the global method getApp() to obtain the current Mini Program instance. The method is generally used to obtain a top-layer application from a page.

  1. var app = getApp();
  2. console.log(app.globalData); // Obtain global data.

When you use the getApp() method, be aware that:

  • You cannot call the getApp() method in the App() function. Use this to obtain the current Mini Program instance.
  • After you obtain the Mini Program instance by calling the getApp() method, do not call a lifecycle callback function without authorization.
  • You need to make a difference between global variables and local page variables. For example:
  1. // a.js
  2. // localValue is only available in a.js.
  3. var localValue = 'a';
  4. // Obtain the app instance.
  5. var app = getApp();
  6. // Obtain global data and modify the data.
  7. app.globalData++;
  1. // b.js
  2. // localValue is only available in b.js.
  3. var localValue = 'b';
  4. // If a.js runs first, the obtained global data is 2.
  5. console.log(getApp().globalData);

The variable localValue is declared in both the a.js file and the b.js file. The two variables do not affect each other, because a local variable in a file is available only in the file.