### [微信小程序之变量和作用域的详细解析](https://www.prosaas.cn/article/17106) **Published:** 2018-08-16T09:23:02 **Author:** 5201314 **Excerpt:** 本篇文章给大家带来的内容是关于微信小程序之变量和作用域的详细解析,有一定的参考价值,有需要的朋友可以参考一下,… 本篇文章给大家带来的内容是关于微信小程序之变量和作用域的详细解析,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。 一,全局变量 在app.js里的变量和方法是全局的。 //app.js App({ onLaunch: function () { // 展示本地存储能力 var logs = wx.getStorageSync('logs') || \[\] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId } }) // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting\['scope.userInfo'\]) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) }, globalData: { userInfo: null, basePath: 'http://127.0.0.1:8086' } }) 在其他页面上,可以通过getApp()获取到里面的方法和变量,console出来后: ![](https://img-blog.csdn.net/20180816140516822?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIzNTIxNjU5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 如果要拿到我们提前设定的basePath,我们可以这样: var app=getApp(); var basePath = app.globalData.basePath; 获取用户的登录信息或者其他方法亦是如此; 二,局部页面内的数据交互 局部页面上的所有数据,都源于js内的data对象: ![](https://img-blog.csdn.net/20180816141016245?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIzNTIxNjU5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 在页面上,可直接使用data内的数据; **赋值:** areaChange:function(e){ //这里获取到了数组角标 console.log(e.detail.value) var index1 = e.detail.value this.setData({ index: index1 }) // console.log("地区:" + this.data.areaListArray\[index1\]) console.log(this.data.areaList\[index1\]) console.log(this.data.areaIdList\[index1\]) } 在方法内,可以直接使用this.setData()定义变量并赋值,只有这样定义的变量能在整个页面内使用。 onLoad: function (options) { var that = this; var app=getApp(); console.log(app); var basePath = app.globalData.basePath; wx.request({ method:"GET", url: basePath +'/area/getAreaByLevel?level=1', success: function (res) { console.log(res); var areaListArray = \[\]; var areaPkIdArray = \[\]; for(var index in res.data.data){ areaListArray.push(res.data.data\[index\].area) areaPkIdArray.push(res.data.data\[index\].pkId) } that.setData({ // projectList : res.data.data.data, // fileUrl: res.data.data.fileSystem areaList: areaListArray, areaIdList: areaPkIdArray }) }, fail: function (res) { console.log(res); } }) }, 如果有this指向不明的,可先将this赋值给其他变量,再进行使用。 本例中是将this赋值给了that,然后再使用的。 相关推荐: 微信小程序实例:如何引入外部js的文件(图文)  微信小程序实例:引入框架WeUI的代码实现 以上就是微信小程序之变量和作用域的详细解析的详细内容,更多请关注知企PROSAAS其它相关文章! **Tags:** console, JS, this, 作用域, 全局变量, 对象, 微信小程序 **Categories:** 后端开发 ---