0

I am wondering if we can use a dynamic variable using "self.variable"

I currently have this class which has two maps. I have a function that apply various things to the map. I want to change map on the fly calling my function with the current map in variable.

googleMap = Class.extend({
    map: null,
    miniMap: null,
    isOverlayVisible: false,
    overlay: null,
});

My script has the following code.

 self.map.fitBounds(bounds);

self.map refers to a variable defined in the class. I also have the variable self.minimap.

How could I have the 'map' inside variable like the following:

function updateMap(currentMap){

    if(typeof currentMap !== "undefined"){
        currentMap = map;
    }
    var currentMap = 'minimap';

    self.currentMap.fitBounds(bounds);
}

updateMap('minimap');

Thanks.

newpoison
  • 914
  • 2
  • 8
  • 20
  • 2
    `self[currentMap]` – Jonas Wilms Apr 23 '18 at 19:36
  • Worth reading: [Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Mikey Apr 23 '18 at 19:37
  • One note I'd like to add: while `self` is not a reserved word, it is a global variable that refers to the current execution context (i.e. the window or the worker global scope). You might want to be careful hiding it. – Máté Safranka Apr 23 '18 at 19:40

1 Answers1

1

You can access Object property by two way

one is . and second is [variable or string]

self[currentMap].fitBounds(bounds);

See this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors.

Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29