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)))

发布了25 篇原创文章 · 获赞 1 · 访问量 1649

猜你喜欢

转载自blog.csdn.net/weixin_43977647/article/details/102977114
今日推荐