将类实例设置为对象(谷歌地图)

时间:2017-11-05 10:49:47

标签: javascript google-maps class object

我正在尝试在我的网站上使用Google地图。我决定创建类“map”,所以我可以使用类方法和对象。

问题是:我希望类构造函数知道此类的每个实例都自动成为Google地图。 所以当我打电话时:

map = new map(location);

我会得到一张Google地图,“this”会引用该地图。这是我的构造函数:

map.prototype = new Element();
map.prototype.constructor = map;

function map (place) {
    this.dom = document.createElement('div');
    document.body.appendChild(this.dom);

    // here I am trying to set "this" to the google map
    // option 1: obviously wrong
    // this = new google.maps.Map(this.dom, {zoom: 9, center: place.location});

    // option 2: overwrites dom, but I want dom to be the div
    // this.dom = new google.maps.Map(this.dom, {zoom: 9, center: place.location});

    //option 3: this works, I don't want to have this extra sub-step using this."map".something...
    this.map = new google.maps.Map(this.dom, {zoom: 9, center: place.location});         


    // call other functions, etc...
};

有没有办法做得更好?无需创建另一个对象属性并将地图放入其中?

1 个答案:

答案 0 :(得分:0)

您可以使用新的Class语法使其更具可读性:

class Map extends google.maps.Map {
  constructor(){
     super(document.body.appendChild(document.createElement('div')), {zoom: 9, center: place.location});

  }

  customMethod(){
     this.whatever();
  }
}