سؤال

I think I am misunderstanding scope or references in JS a little bit.

I'm using Leaflet to initiate a new map object. My code is something like this:

var revealing = (function() {
    var mapEl = "#map";
    var mapName = "map";
    var mapboxMap = '----';
    var map;


    var init = function() {
        map = L.mapbox.map(mapName, mapboxMap);
        map.setView([40, -100], 5);
    }

    return {
        "init": init
    }

}());

If I reference 'map' inside the init function, I get what I want. But anywhere else that I reference map (either within the function or elsewhere via the 'revealing' object, I get a reference to the html object that leafleft (L.mapbox...) has created, rather than the instantiated object I get inside init().

Any help would be greatly appreciated.

هل كانت مفيدة؟

المحلول

You haven't shown the code where you're having trouble (e.g., accessing map and not getting what you expect), but I suspect the problem isn't scope, it's timing.

Anywhere within your big anonymous function, map will resolve to the map variable you've declared within that function. But that variable has the value undefined until init sets it to something. At that point, it has the value that init assigns to it.

More in this example:

var revealing = (function() {
    var mapEl = "#map";
    var mapName = "map";
    var mapboxMap = '----';
    var map;


    var init = function() {
        map = L.mapbox.map(mapName, mapboxMap);
        map.setView([40, -100], 5);
    }

    var useMap = function() {
        console.log(map); // <============== 1 - See 3 and 4 below
    };

    console.log(map);     // <============== 2 - Shows "undefined"

    return {
        "init": init,
        "useMap": useMap
    }

}());
revealing.useMap();       // <============== 3 - Shows "undefined"
revealing.init();
revealing.useMap();       // <============== 4 - Shows the map created in `init`
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top