作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在我的网站上使用 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/
leaflet:一个开源并且对移动端友好的交互式地图 JavaScript 库 中文文档: https://leafletjs.cn/reference.html 官网(英文): ht
我是一名优秀的程序员,十分优秀!