问题是这样的。利用微信的位置获取API(wx.getLocation())函数,在监听SUCCESS成功函数内,得到了返回值后,将返回值赋值到 this.data 对象内的 属性。但是出现了这种情况,很无解。
//获取应用实例 var app = getApp(); var conf = require( '../../conf/conf.js' ); Page({ data: { motto: 'Hello World' , latitude: '' , longitude: '' }, onLoad: function () { var that = this that.getLocationInfo() console.log( "我是第20行DEBUG:" +that.data.longitude+ "," +that.data.latitude) console.log( "我是motto:" +that.data.motto) }, //获得天气信息 getWeaterInfo: function (lon,lat) { var that = this console.log( "我是第33行DEBUG:" +that.data.longitude+ "," +that.data.latitude) }, //获得地址信息 getLocationInfo: function () { var that = this wx.getLocation({ type: 'wgs84' , success: function (locationInfo){ that.data.latitude = locationInfo.latitude that.data.longitude = locationInfo.longitude that.getWeaterInfo(locationInfo.longitude,locationInfo.latitude) } }) } }) |
流程如下:
1.页面加载后,调用 that.getLocationInfo()
2.在 getLocationInfo() 函数内,使用了 wx.getLocation API,在 SUCCESS 函数内,进行了 this.data 以及 一个函数调用 that.getWeaterInfo()
3.调用函数that.getWeaterInfo(),直接输出了值。这里显示的值是正常的。
4.当函数执行完毕,运行到第20行时候,再次打印 this.data 内的经纬度数值,发现变为空的了。
5.但是 this.data.motto 的数值打印了,不是空的。
疑问:
1.所有API的返回值只能在SUCCESS范围内有效吗?若需要赋值给 this.data 该怎么做?
2.能解释下吗?谢谢
备注:
探究了一会,以为是对象(this)问题。修改了代码如下:
//index.js //获取应用实例 var app = getApp(); var conf = require( '../../conf/conf.js' ); Page({ data: { motto: 'Hello World' , latitude: '' , longitude: '' }, onLoad: function () { var that = this this .getLocationInfo(that) console.log( "我是第20行DEBUG:" +that.data.longitude+ "," +that.data.latitude) console.log( "对象一致:" +(that === this )) console.log( "我是motto:" +that.data.motto) }, //获得天气信息 getWeaterInfo: function (lon,lat,that) { console.log( "我是第33行DEBUG:" +that.data.longitude+ "," +that.data.latitude) console.log( "对象一致:" +(that === this )) }, //获得地址信息 getLocationInfo: function (that) { wx.getLocation({ type: 'wgs84' , success: function (locationInfo){ that.data.latitude = locationInfo.latitude that.data.longitude = locationInfo.longitude that.getWeaterInfo(locationInfo.longitude,locationInfo.latitude,that) } }) } }) |
上面代码,我将 this 复制给了 that 。然后一直传递下去。发现在同一个对象下,之前的问题还是出现了。
究竟是什么原因呢????????????????????