getApp

A global getApp() function is available for obtaining the instance of currently running Mini Program. This is generally used in page to get the top-level app.

copy
var app = getApp()
console.log(app.globalData) // Get globalData

Note:

  • Do not call getApp() in App(). Instead, use this to get the app instance.
  • After the instance is obtained with getApp(), do not call the lifecycle function of App.
  • Please distinguish App global data and Page global data.

The global data can be set in App(). The individual sub-pages can get the global application instance through the global function getApp(). Here is an example.

copy
// app.js
App({
  globalData: 1
})
copy
// a.js
// localValue effective only in a.js
var localValue = 'a'
// generating app instance
var app = getApp()
// get global data and change it
app.globalData++
copy
// b.js
// localValue effective only in b.js
var localValue = 'b'
// if a.js runs first, the globalData returns 2
console.log(getApp().globalData)

In the codes shown above, both the a.js and b.js have declared the variable localValue, but they will not affect each other, because the variable and function of each script take effect only in their own scope.