[英]OO JS & Google Maps API: What am I doing wrong?
這是我第一次涉足OO JS,遇到問題。
理想情況下,在這種情況下,我有一個mapLocation對象,我可以傳遞坐標,圖標,HTML點擊顯示,就是這樣。 我將它添加到我在頁面上的谷歌地圖上,我有一些可重復使用的東西。 顯然這將在以后重構。
另外,我對我的代碼目前的處理方式並不特別滿意。 :)
這是我想出的對象。
function mapLocation() {
this.lat = 0;
this.lng = 0;
this.icon = '';
this.html = '';
this.getLocation = getLocation;
}
function getLocation() {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var letteredIcon = new GIcon(baseIcon);
letteredIcon.image = this.icon;
var point = new GLatLng(this.lat, this.lng);
var marker = new GMarker(point, { icon:letteredIcon });
function show() {
marker.openInfoWindowHtml('Lat: '+this.lat+'<br />Lng: '+this.lng+'<br /><img src="'+this.icon+'" />');
}
alert(this.lat);
GEvent.addListener(marker, "click", show);
return marker;
}
這是我的實施。
var a = new mapLocation;
a.lat = 52.136369;
a.lng = -106.696299;
a.icon = 'http://www.google.com/mapfiles/markerA.png';
a.html = 'asdf fdsa';
var b = a.getLocation();
map.addOverlay(b);
所以我得到了窗口,我的標記,但show()函數彈出未定義。
我很好奇我做錯了什么 - 我怎么想錯了 - 在這個問題上。
謝謝你的樣子。
var _this = this;
function show() {
marker.openInfoWindowHtml('Lat: '+_this.lat+'<br />Lng: '+_this.lng+'<br /><img src="'+_this.icon+'" />');
}
請記住,除非將函數作為對象的成員調用,否則此===窗口。
此外,表達所有這一切的更簡潔方法是:
function mapLocation() {
// constructor stuff
}
mapLocation.prototype = {
getLocation: function() {
// code for getLocation
}
};
然后,您不必在構造函數中分配this.getLocation。
不能沒有那些額外的功能,但我想這是一個'這個'參考問題,因為你的show函數沒有創建一個閉包。
試試這個(編輯:我是個白痴,忘了'這個'問題):
function show() {
var x = this;
return function(){marker.openInfoWindowHtml('Lat: '+x.lat+'<br />Lng: '+x.lng+'<br /><img src="'+x.icon+'" />');}
}
GEvent.addListener(marker, "click", show());
至於OOJS ......評論解釋:
//convention is to name JS classes with an uppercase character
function MapLocation(params)
{
//instantiate from a params object to keep a flexible contructor signature
//(similarly you can use the native arguments object but I prefer to be explicit)
this.lat = (params.lat ? params.lat : 0);
this.lng = (params.lng ? params.lng : 0);
this.icon = (params.icon ? params.icon : '');
this.html = (params.html ? params.html : '');
//keep methods contained within the class definition
if (typeof(this.geolocation) == 'undefined') //execute once
{
//by binding methods with prototype you only construct a single instance of the function
MapLocation.prototype.getLocation = function ()
{
/* ... */
}
}
}
//property set at constructor
var a = new MapLocation({lat:52.136369, lng:-106.696299, icon: 'http://www.google.com/mapfiles/markerA.png'});
//deferred property setting
a.html = 'asdf fdsa';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.