简体   繁体   English

JS揭示模块模式范围/参考

[英]JS Revealing Module Pattern scope / references

I think I am misunderstanding scope or references in JS a little bit. 我认为我有点误解了JS中的作用域或引用。

I'm using Leaflet to initiate a new map object. 我正在使用Leaflet来初始化一个新的地图对象。 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. 如果我在init函数中引用“ map”,我将得到想要的。 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(). 但是我引用地图的其他任何地方(在函数内部或通过“显示”对象的其他地方,我都引用了leafleft(L.mapbox ...)创建的html对象,而不是我进入内部的实例化对象。在里面()。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You haven't shown the code where you're having trouble (eg, accessing map and not getting what you expect), but I suspect the problem isn't scope, it's timing . 您没有在遇到问题的地方显示代码(例如,访问map而不得到期望的结果),但是我怀疑问题不在范围内,这是时间上的问题

Anywhere within your big anonymous function, map will resolve to the map variable you've declared within that function. 在大型匿名函数中的任何地方, map都将解析为您在该函数中声明的map变量。 But that variable has the value undefined until init sets it to something. 但是该变量具有undefined的值,直到init将其设置为某种值为止。 At that point, it has the value that init assigns to it. 此时,它具有init为其分配的值。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM