Home > Article > WeChat Applet > WeChat Mini Program Tutorial Modularization
File Scope
Variables and functions declared in a JavaScript file are only valid in that file; variables and functions with the same name can be declared in different files without affecting each other.
You can get the global application instance through the global function getApp(). If you need global data, you can set it in App(), such as:
// app.js App({ globalData: 1 })
// a.js // The localValue can only be used in file a.js. var localValue = 'a' // Get the app instance. var app = getApp() // Get the global data and change it. app.globalData++
// b.js // You can redefine localValue in file b.js, without interference with the localValue in a.js. var localValue = 'b' // If a.js it run before b.js, now the globalData shoule be 2. console.log(getApp().globalData)
Modularization
We can put some common code Extract it into a separate js file as a module. Modules can only expose interfaces to the outside world through module.exports.
// common.js function sayHello(name) { console.log('Hello ' + name + '!') } module.exports = { sayHello: sayHello }
In the files that need to use these modules, use require(path) to introduce the public code.
var common = require('common.js') Page({ helloMINA: function() { common.sayHello('MINA') } })
The above is the modular content of the WeChat applet tutorial. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!