在javascript文件中声明的变量和函数只在该文件中有效;不同的文件中可以声明相同名字的变量和函数,不会互相影响。
通过全局函数getapp()可以获取全局的应用实例,如果需要全局的数据可以在app()中设置,如:
// 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) 我们可以将一些公共的代码抽离成为一个单独的js文件,作为一个模块。模块只有通过module.exports或者 exports才能对外暴露接口。
需要注意的是:
exports是module.exports的一个引用,因此在模块里边随意更改exports的指向会造成未知的错误。所以我们更推荐开发者采用module.exports来暴露模块接口,除非你已经清晰知道这两者的关系。node_modules,开发者需要使用到node_modules时候建议拷贝出相关的代码到小程序的目录中。// common.js
function sayhello(name) {
console.log('hello ${name} !')
}
function saygoodbye(name) {
console.log('goodbye ${name} !')
}
module.exports.sayhello = sayhello
exports.saygoodbye = saygoodbye 在需要使用这些模块的文件中,使用require(path)将公共代码引入。
var common = require('common.js')
page({
hellomina: function() {
common.sayhello('mina')
}
goodbyemina: function() {
common.saygoodbye('mina')
}
})1. tip:require暂时不支持绝对路径