微信小程序踩坑之一[thist]使用技巧

刚上手小程序 时,习惯把this当成jquery中的$(this)来用,实际上这两个还是有差别的

在页面方法中调用其他方法,一般是用this.function(),直接调用小程序 的方法或函数则是用wx.function

多层方法下的时候,则要给this定义一个变量才能使用,否则会一直报方法没有定义

下面踩坑之一的是调用地理定位时给经纬度赋值时碰到的

Page({
  data: {
    scale:18,
    latitude:0,
    longitude:0,
  },
  onLoad:function(options){
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })
  },
  onShow:function(){
    this.mapCtx = wx.createMapContext('myMap');
    this.moveToLocation;
  },
  onReady: function (e) {
    
  },
  moveToLocation:function(){
    this.mapCtx.moveToLocation()
  }

})