Javascript letter object: why can't I do this?

I have the following (simplified) object literal. The icon method uses closure to hide the icon variable that I would like to have as an associative array for subsequent searches.

var MapListings = {
    icons: function () {
        var allIcons = [] ;

        return {
            add: function (iconType, iconImage) {
                var icon = new GIcon(MapListings.baseIcon);
                icon.image = iconImage;
                allIcons[iconType] = icon; // fails, but this is what I want
                // allIcons.push(icon); // works, but this is not what I want
            },
            get: function () {
                return allIcons;
            }
        };

    } ()
}

I add elements to the icon object as follows:

MapListings.icons.add("c7", "/images/maps/blue.png");
MapListings.icons.add("c8", "/images/maps/red.png");

The following does not work:

allIcons[iconType] = icon;

But it does:

allIcons.push(icon);

Outside of closure, the associative array style works fine, maybe there is a conflict with jQuery? The error I get in firebug a, undefined , looks from the library. I would like to maintain an associative array style.

Any ideas?

Update

This conflict seems to come from Google maps. Strange, not sure about that.

Dumbass Update

, GIcon(), . , .

baseIcon: function () {
    var base = new GIcon();
    base.shadow = '/images/maps/shadow.png';
    base.iconSize = new GSize(12, 20);
    base.shadowSize = new GSize(22, 20);
    base.iconAnchor = new GPoint(6, 20);
    base.infoWindowAnchor = new GPoint(5, 1);
    return base;
}

MapListings.baseIcon MapListings.baseIcon()! D'

+3
3

, var allIcons = {}

EDIT: , . , ?

№ 2. allIcons MapListings?

№ 3: , , , , ? Google, , , , .

function GIcon(){};
var MapListings = {
    icons: function () {
        var allIcons = [] ;

        return {
            add: function (iconType, iconImage) {
                var icon = new GIcon(MapListings.baseIcon);
                icon.image = iconImage;
                allIcons[iconType] = icon; // fails, but this is what I want
                // allIcons.push(icon); // works, but this is not what I want
                window.x = allIcons
            },
            get: function () {
                return allIcons;
            }
        };

    } ()
};

MapListings.icons.add("c7", "/images/maps/blue.png");
MapListings.icons.add("c8", "/images/maps/red.png");

alert( MapListings.icons.get()['c8']['image'] )

.length, c7 c8.

x = MapListings.icons.get();
for ( var prop in x ) {
    if ( x.hasOwnProperty(prop ) ) {
        alert( x[prop]['image'] )
    }
}
+4

, , , . add :

MapListings.icons["c7"]

:

add: function (iconType, iconImage) { 
    MapListings.icons[iconType] = iconImage;
}, 
+1

allIcons[iconType] = icon; , allIcons , . allIcons {}. .

0

Source: https://habr.com/ru/post/1754464/


All Articles