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.
var app = getApp();
console.log(app.globalData); // Obtain global data.
When you use the getApp()
method, be aware that:
- You cannot call the
getApp()
method in theApp()
function. Usethis
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:
// a.js
// localValue is only available in a.js.
var localValue = 'a';
// Obtain the app instance.
var app = getApp();
// Obtain global data and modify the data.
app.globalData++;
// b.js
// localValue is only available in b.js.
var localValue = 'b';
// If a.js runs first, the obtained global data is 2.
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.