这篇文章主要介绍微信小程序中文件作用域的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
文件作用域
在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 才能对外暴露接口。
需要注意的是:
//commont.jsfunction sayHello(name){
console.log('------ hello ' + name +'=====');
}
module.exports.sayHello = sayHello;
//index.jsvar common = require('../commont/commont.js');
Page({ //加载视图的时候
onLoad:function (){
//调用
common.sayHello('dqk');
})
控制台输出:

提示
require 暂时不支持绝对路径
以上是“微信小程序中文件作用域的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!