微信小程序 教程之模块化
更新时间:2016年10月17日 16:27:48 投稿:lqh
这篇文章主要介绍了微信小程序 模块化的相关资料,需要的朋友可以参考下
系列文章:
文件作用域
在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才能对外暴露接口。
// common.js
function sayHello(name) {
console.log('Hello ' + name + '!')
}
module.exports = {
sayHello: sayHello
}
在需要使用这些模块的文件中,使用require(path)将公共代码引入。
var common = require('common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
}
})
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
JSON字符串转换JSONObject和JSONArray的方法
这篇文章主要介绍了JSON字符串转换JSONObject和JSONArray的方法的相关资料,需要的朋友可以参考下2016-06-06
fs-extra实现yarn create tlist创建示例详解
这篇文章主要为大家介绍了fs-extra实现yarn create tlist创建示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-01-01


最新评论