gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:00:59 24 4
gpt4 key购买 nike

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

问题是:我希望类构造函数知道该类的每个实例自动都是一个 Google map 。所以当我打电话时:

map = new map(location);

我将获得一张 Google map ,“this”将指该 map 。这是我的构造函数:

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...
};

有什么办法可以做得更好吗?无需创建另一个对象属性并将 map 放入其中?

最佳答案

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

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

}

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

关于javascript - 将类实例设置为对象(谷歌地图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com