在微信小程序中咱们通常经过如下方式来修改data中的数据html
this.setData({ index1: e.detail.value })
好比在函数里面修改数据前端
bindFaChange1: function (e) { this.setData({ index1: e.detail.value }) }
可是当咱们经过wx.request请求网络数据成功后绑定数据时候报如下错误es6
this.setData is not a function
代码以下:json
doCalc:function(){ wx.request({ url: url, method:'POST', header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { if (res.data.code == 0){ this.setData({ maxCount: res.data.maxCount }); } } }) }
这是由于this做用域指向问题 ,success函数实际是一个闭包 , 没法直接经过this来setData小程序
那么须要怎么修改呢?微信小程序
咱们经过将当前对象赋给一个新的对象微信
var _this = this;网络
而后使用_this 来setData就好了闭包
完整代码app
doCalc:function(){ var _this = this; wx.request({ url: url, method:'POST', header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { if (res.data.code == 0){ _this.setData({ maxCount: res.data.maxCount }); } } }) }
另外说一下 , 在es6中 , 使用箭头函数是不存在这个问题的
例如 :
setTimeout( () => { console.log(this.type + ' says ' + say) }, 1000)
当咱们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
并非由于箭头函数内部有绑定this的机制,实际缘由是箭头函数根本没有本身的this,它的this是继承外面的,所以内部的this就是外层代码块的this。
做者:fozero
声明:原创文章,转载请注明出处,谢谢!http://www.cnblogs.com/fozero/p/7841488.html 标签:前端,微信小程序,ES6