小编给大家分享一下微信小程序模块化和文件作用域的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
文件作用域
在JavaScript文件中声明的变量和函数只在该文件中有效;不同的文件中可以声明相同名字的变量和函数,不会互相影响。
通过全局函数getApp()
可以获取全局的应用实例,如果需要全局的数据可以在App()
中设置,如:
// app.jsApp({
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
才能对外暴露接口。
需要注意的是:
// common.jsfunction 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')
}})
以上是“微信小程序模块化和文件作用域的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!