簡體   English   中英

js singleton-如何避免通過名稱空間訪問類成員

[英]js singleton - how to avoid accessing class members via the namespace

我正在嘗試改善我的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);
        });
    }

};

直接在對象上的函數的第一行應該是...

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

然后,在您的內部函數中,使用that交換this引用。

這是因為內部函數this指向window

如果您使用的是jQuery,請看一下proxy()方法:

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

此方法是專門設計來的范圍迫使this特定對象。 我個人更喜歡PrototypeJS bind()的語法:

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

...但是盡管我更喜歡PrototypeJS而不是jQuery,但似乎戰斗已經打敗了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM