微信小程序中的文件作用域和模块化
文件作用域
(1)在 JavaScript 文件中声明的变量和函数只在该文件中有效;(变量当前页面有效)
(2)不同的文件中可以声明相同名字的变量和函数,不会互相影响。(当前页面和其他页面的变量和函数无影响)
如,全局函数:
// app.js
App({
globalData: 1
})
a.js文件:
// 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文件:// 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)
模块化
公共的代码单独封装在一个 js 文件,作为一个整体(模块)。
模块只有通过 module.exports
或者 exports
才能对外暴露接口,(建议使用module.exports)
//common.js文件
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
//other.js 文件,通过使用 require(path)
将公共代码引入
var common = require('common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
},
goodbyeMINA: function() {
common.sayGoodbye('MINA')
}
})
注:require 暂时不支持绝对路径。