箭头函数和普通函数的区别
最近写vue调用微信接口遇到的一个问题,这边记录一下:
这是一开始的写法
wx.getLocation({
type: 'wgs84', //默认为wgs84的gps坐标,可传入火星坐标'gcj02'
success: function(res) {
this.map.center.lat = res.latitude; // 纬度,浮点数,范围为90 ~ -90
this.map.center.lng = res.longitude; // 经度,浮点数,范围为180 ~ -180
//坐标转换
this.changCo();
}
});
发现 this.map.center 没值,后来换成以下写法能正常赋值:
wx.getLocation({
type: 'wgs84', //默认为wgs84的gps坐标,可传入火星坐标'gcj02'
success: res => {
this.map.center.lat = res.latitude; // 纬度,浮点数,范围为90 ~ -90
this.map.center.lng = res.longitude; // 经度,浮点数,范围为180 ~ -180
//坐标转换
this.changCo();
}
});
区别:
1、箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向
2、普通函数的this指向调用它的那个对象