Using object literals for the first time and it seems I don’t quite understand them right. What I need is private variables with the scope of the object and therefore accessible to all functions in the object literal.
Here’s the issue:
I have a simple object literal for a map object
var mapObj = {
init: function (lat, lng, documentID) {
var myOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(documentID),
myOptions);
return map;
},
setMarker: function (lat, lng, map, contentObj) {
var myLatlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Hello World!",
content: contentObj
});
}
};
This is all fine, and I get to use it as mapObj.init(….) and mapObj.setMarker(…) which work perfectly.
What I want to be able to do is store some of these variable values – like ‘map’ in the init() method, and then have it accessible for other methods. For e.g. I should not need to pass ‘map’ in the setMarker, as the mapObj should hold the map internally after the init method.
Similarly I’d like to be able to do mapObj.getMap() to access the map object created in init.
I’m unable to figure out how it works. Declaring var map as
var mapObj {
var map
}
for e.g throws errors.
Am I expecting this to work too much like C#? Should I be using the classic javascript ‘class’ constructions? Any pointers will help so I can move on.
Thanks
Just wrap it in a function like so:
Now
mapis only available inside that function (and all functions it contains).mapObjis available outside.