May 18, 2021 WeChat Mini Program Development Document
Variables and functions declared in a JavaScript file are valid only in that file;
The global function
getApp()
to get a global instance of the app, and if you need global data, you can set it up in the
App()
for example:
// 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)
We can pull some common code out into a separate js file as a module.
The module can only
expose the interface to the outside world through
module.exports
or
exports
It is important to note that:
exports
are
module.exports
so changing the pointing of
exports
at will in the module can cause unknown errors.
So we recommend that
module.exports
expose module interfaces unless you already know the relationship.
node_modules
and
node_modules
time to recommend copying the relevant code into the directory of the small program.
// common.js
function sayHello(name) {
console.log('Hello ${name} !')
}
function sayGoodbye(name) {
console.log('Goodbye ${name} !')
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
In files that need to use these modules,
require(path)
to introduce public code.
var common = require('common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
}
goodbyeMINA: function() {
common.sayGoodbye('MINA')
}
})
1. tip: Require does
require
absolute paths for the time being