从参数扩展类

时间:2017-06-19 15:45:03

标签: javascript class ecmascript-6

在一个理想的世界里,我可以导入google并扩展它,并在我的班级中使用它。

import google from 'google'

class GoogleMapsPopover extends google.maps.OverlayView{
  constructor ({point, map}) {
    this.bounds_ = new google.maps.LatLngBounds(point, point)
    this.map_ = map
    this.div_ = null
    this.setMap(map)
  }
}

但是我想将google作为参数传递给GoogleMapsPopover类。

你不能super而不能像这样扩展:

class GoogleMapsPopover {
  constructor ({google, point, map}) {
    super(google.maps.OverlayView)
    this.google = google
    this.bounds_ = new this.google.maps.LatLngBounds(point, point)
    this.map_ = map
    this.div_ = null
    this.setMap(map)
  }
}

您无法像这样设置this的值:

class GoogleMapsPopover {
  constructor ({google, point, map}) {
    this = google.maps.OverlayView
    this.google = google
    this.bounds_ = new this.google.maps.LatLngBounds(point, point)
    this.map_ = map
    this.div_ = null
    this.setMap(map)
  }
}

我能想到的唯一选择是将一个类包装在一个函数中,这有点像hacky。

这样的事情:

export const getGoogleMapsPopoverClass = (google) => {
  return class GoogleMapsPopover extends google.maps.OverlayView {
    constructor ({point, map}) {
      super()
      this.bounds_ = new google.maps.LatLngBounds(point, point)
      this.map_ = map
      this.div_ = null
      this.setMap(map)
    }
  }
}

const GoogleMapsPopover = getGoogleMapsPopoverClass(google)

0 个答案:

没有答案