在绝大多数情况下,函数的调用方式决定了this的值。this不能在执行期间被赋值,并且在每次函数被调用时this的值也可能会不同。
在微信小程序中 我就遇到的一些问题
requestName: function (name) {
console.log("开始请求数据")
wx.request({
url: 'xxx',
success(res) {
console.log(res.data.title);
this.setData({
rename:res.data.data.title
})
}
})
console.log("数据请求完毕");
},
代码的作用是请求一个接口 然后把数据放到rename里面
但是这样写总是报了一个奇怪的错误
后来发现是this的指定有问题
按照以下写法就没问题了
requestName: function (name) {
var that = this;
console.log("开始请求数据")
wx.request({
url: 'http://hn216.api.yesapi.cn/?service=',
success(res) {
console.log(res.data.title);
that.setData({
rename:res.data.data.title
})
}
})
console.log("数据请求完毕");
},