javascript中遇到this指针问题的说明

问题描述

在Vue框架中写了一个global.vue用来存放Vue文件中的全局变量,是一种代替Vue本身store的方法,在global.vue中一开始写了一个函数如下:

 function panAndZoom (point) {
    let that = this
    this.map.panTo(point)
    setTimeout(function () {
      that.map.centerAndZoom(point, 15) 
    }, 500)

其中map是百度地图API中定义好的变量在global.vue中又保存了一遍,它包含有panTo,panAndZoom这样的函数

问题:我想把所有的函数放在一个类下面,但是这个地方的panAndZoom函数中的this指针指向的是const Function这个类,类里面没有定义map这个变量,怎么样才能调用到map这个变量,如下想法:

 const Functions = {
  panAndZoom: function (point) {
    let that = this
    this.map.panTo(point)
    setTimeout(function () {
      that.map.centerAndZoom(point, 15)
    }, 500)
  }
}

解决方案

在调用该函数的时候利用js中的call函数来规定this指针指向内容
global.vue中代码不变如下:

 const Functions = {
  panAndZoom: function (point) {
    let that = this
    this.map.panTo(point)
    setTimeout(function () {
      that.map.centerAndZoom(point, 15)
    }, 500)
  }
}

调用时候的代码如下:

//其中this.GLOBAL指代是就是global.vue
//在main.js中有import global from '../public/global'和Vue.prototype.GLOBAL = global
this.GLOBAL.Functions.panAndZoom.call(this.GLOBAL, (new BMap.Point(typePosition.positions[i].lng, typePosition.positions[i].lat)))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值