2.js的闭包 和回调函数
//index.js //获取应用实例 const app = getApp() Page({ data: { phoneNum:null, resultInfo:null }, inputXXX:function(event){ //这里的this 可以直接使用 this.setData({phoneNum:event.detail.value}) }, btnclick:function(){ //这里是闭包了,this 不能直接使用 var thisPage = this app.getWeatherInfo(this.data.phoneNum,function(data){ //回调函数,传入的data 可以直接使用 thisPage.setData({resultInfo:data}) }) }, })
这里的函数,自定义的回调
getWeatherInfo:function(num,cb){ wx.request({ url: 'http://localhost:8080/test/data', data: { phoneNum:num }, method:'POST', header: { 'content-type': 'application/x-www-form-urlencoded' // 默认值 }, success: function (res) { // console.log(res.data) //该函数可以将数据返回 cb(res.data); } }) }
感谢阅读博客,欢迎向博主讨论问题。