Modularization
Some common codes can be extracted into a separate JS file as a module. Modules can only expose interfaces to the outside world through module.exports or exports.
TIP
exports is a reference to module.exports, so changing the direction of exports in the module will cause unknown errors. Therefore, it is recommended that developers use module.exports to expose module interfaces unless you already know the relationship between the two.
// common.js
function sayHello(name) {
console.log(Hello ${name} !)
}
function sayGoodbye(name) {
console.log(Goodbye ${name} !)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbyeFile 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.
Global object
Similar to the browser's Window and NodeJS's global, mini-games also have a global object GameGlobal. GameGlobal can be used to pass variables in multiple files.
// a.js
GameGlobal.globalData = 1// b.js
console.log(GameGlobal.globalData) // 输出 "1"