js singleton - 如何避免通过命名空间访问类成员

时间:2011-11-18 00:28:59

标签: javascript singleton this javascript-namespaces

我正在努力改进我的Javascript编码风格,并且已经阅读了命名空间的东西。

但是我似乎无法在任何地方使用“this”关键字 - 而是我只能通过命名空间(在本例中为“oldMap”)从匿名函数中访问我的类属性。这意味着我无法在不更改代码的情况下更改命名空间ID - 这似乎可能是错误的。

这是我构建的类 - 它实际上似乎正常工作。 (对不起,这很长)。

对于我正在做的是/错的感激之情的任何建议/提示。感谢

var oldMap = {

    map : null,

    center : {lat:50, lng:20, zoom:3}, 

    drawn : false,

    data : {},

    divId : "oldMap",

    url : "php/getMapData.php",

    infowindow : new google.maps.InfoWindow({ 
        size: new google.maps.Size(150,50)
    }),

    init : function () {

        if (!this.drawn){
            $.getJSON(
                this.url,
                function(d){
                    if(d){
                        $.extend(oldMap.data,d);

                        var latlng = new google.maps.LatLng(oldMap.center.lat, oldMap.center.lng);
                        var myOptions = {
                            zoom: oldMap.center.zoom,
                            center: latlng,
                            mapTypeId: google.maps.MapTypeId.TERRAIN
                        };

                        // create the map
                        map = new google.maps.Map(document.getElementById("oldMap"),myOptions);

                        // create the legend
                        var legendDiv = document.createElement('DIV');
                        legendDiv.innerHTML = '<div id="legend"><img src="images/markers/legend-blur.png"></div>';
                        map.controls[google.maps.ControlPosition.TOP_LEFT].push(legendDiv);

                        google.maps.event.addListener(map, 'click', function() {
                            infowindow.close();
                        });

                        // Set the info window html template
                        var infoWindowTemplate = "<div id='balloon'>{{#url2}}<img src='{{url2}}' />{{/url2}}<h2>{{project_name}}</h2><p><b>Amount</b> &euro; {{cost}}</p><p><b>Country</b> {{country}}</p><p><b>Year</b> {{year}}</p><p><b>Project Type</b> {{project_type}}</p><p>{{description}}</p>{{#url}}<p><a target='_blank' href='{{url}}'>More info</a></p>{{/url}}</div>"

                        // loop through the projects
                        for(var m in oldMap.data) {

                            // if the project has a marker type defined
                            if (oldMap.data[m].marker) {

                                // point
                                var point = new google.maps.LatLng(oldMap.data[m].lat, oldMap.data[m].longtd); 

                                // create HTML for info window
                                var infoHtml = Mustache.to_html(infoWindowTemplate, oldMap.data[m]);

                                // icon
                                var icon = new google.maps.MarkerImage(
                                    "images/markers/33px/" + oldMap.data[m].marker + ".png",
                                    new google.maps.Size(33,33)
                                );

                                // create a marker for this project
                                var marker = oldMap.createMarker(point,infoHtml,icon);
                            }
                        }

                        oldMap.drawn = true;
                    }
                }
            )
        }
    },


    createMarker : function (latlng, html, icon) {

        // create the marker
        var marker = new google.maps.Marker({
            position: latlng,
            icon: icon,
            map: map,
            zIndex: Math.round(latlng.lat()*-100000)<<5
        });

        // open info window when marker clicked
        google.maps.event.addListener(marker, 'click', function() {
            oldMap.infowindow.setContent(html); 
            oldMap.infowindow.open(map,marker);
        });
    }

};

2 个答案:

答案 0 :(得分:1)

直接在对象上的第一行函数应该是......

function () {
    var that = this;
    ...
}

然后,在您的内部函数中,将对this的引用与that交换。

这是因为内部函数“this指向window

答案 1 :(得分:0)

如果您正在使用jQuery,请查看proxy()方法:

http://api.jquery.com/jQuery.proxy/

此方法专门用于强制this范围到特定对象。我个人更喜欢PrototypeJS bind()的语法:

http://api.prototypejs.org/language/Function/prototype/bind/

...但是,虽然我更喜欢PrototypeJS和jQuery,但似乎已经战斗并且已经失败了。