简体   繁体   English

Javascript对象文字范围问题?

[英]Javascript Object Literal Scope Issue?

I'm having a hard time understanding why this.$map and this.markers are undefined. 我很难理解为什么this.$mapthis.markers未定义。 Here's the code I'm working with and I have added comments where I expect these variables to supply a value: 这是我正在使用的代码,并且在我希望这些变量提供值的地方添加了注释:

(function($) {
    'use strict';

    var A = {

        /**
         * Initialize the A object
         */
        init: function() {
            this.$map = this.renderMap();
            this.markers = this.getMarkers();

            this.renderMarkers();
        },

        renderMap: function() {

            var url = 'http://a.tiles.mapbox.com/v3/delewis.map-i3eukewg.jsonp';

            // Get metadata about the map from MapBox
            wax.tilejson(url, function(tilejson) {
                var map = new L.Map('map', {zoomControl: false});

                var ma = new L.LatLng(42.2625, -71.8028);

                map.setView(ma, 8);

                // Add MapBox Streets as a base layer
                map.addLayer(new wax.leaf.connector(tilejson));

                return function() {
                    return map;
                };
            });
        },

        renderMarkers: function() {
            var geojsonLayer = new L.GeoJSON(null, {
                pointToLayer: function (latlng){
                    return new L.CircleMarker(latlng, {
                        radius: 8,
                        fillColor: "#ff7800",
                        color: "#000",
                        weight: 1,
                        opacity: 1,
                        fillOpacity: 0.8
                    });
                }
            });

            geojsonLayer.addGeoJSON(this.markers); // this.markers is undefined
            this.$map.addLayer(geojsonLayer); // this.$map is undefined

        },

        getMarkers: function() {
            $.getJSON("/geojson/", function (data) {
                return data;
            });
        }
    };

    /**
     * A interactions
     */
    $(document).ready(function() {
        A.init()
    });

})(jQuery.noConflict());

I have spent much of the day searching and I think I'm missing something fundamental here, but I don't get it. 我花了整整一天的时间进行搜索,但我认为这里缺少一些基本知识,但我不明白。

Neither the renderMap , nor getMarkers methods return any value, consequently their return value is undefined . renderMapgetMarkers方法都不返回任何值,因此它们的返回值是undefined

It looks like you are trying to initialize these fields from an ajax request, which is not necessarily a good idea. 看来您正在尝试通过ajax请求初始化这些字段,但这不一定是一个好主意。

What you probably ought to do is something like: 您可能应该做的是:

getMarkers: function(callback){
    var result = this;
    $.getJSON("url", function(jsonData){ 
        result.markers = jsonData; 
        if(callback) callback()
     });
},

which will lazily initialize the fields of the object as they become available. 当它们可用时,它将懒惰地初始化对象的字段。

NB : AJAX is asynchronous you cannot rely on this callback setting the member quickly, or indeed ever (it could fail). 注意 :AJAX是异步的,您不能依靠此回调快速设置成员,或者甚至永远(可能失败)。 This suggests you need to think a bit more about your design, and try to use callbacks more. 这表明您需要多考虑一些设计,并尝试更多使用回调。

eg modify the getMarkers and renderMap functions as above to take a callback that is called after the data is stored then change init to: 例如,按上述方法修改getMarkersrenderMap函数,以获取存储数据后调用的回调,然后将init更改为:

init: function(){
    var res = this;
    var post_init_callback = function(){
        if(res.$map != undefined && res.markers!=undefined){
            //this will only run after both ajax calls are complete
            res.renderMarkers();  
        }
    };
    this.getMarkers(post_init_callback);
    this.renderMap(post_init_callback);
},

The problem here is that you call return inside another function. 这里的问题是您在另一个函数中调用了return。 What you're essentially doing is defining getMarkers (the simplest example) as this: 您实际上所做的是将getMarkers (最简单的示例)定义为:

getMarkers: function() {
    $.getJSON('/geojson/', some_random_func);
}

At which point it becomes obious that getMarkers doesn't actually return anything (ergo undefined). 在这一点上,很令人讨厌的是getMarkers实际上没有返回任何东西(ergo undefined)。 The same goes for your renderMap function. renderMap函数也是如此。 Also in this case your "some_random_func" is defined as function(data) { return data; } 同样在这种情况下,您的“ some_random_func”被定义为function(data) { return data; } function(data) { return data; } but what does it return it to? function(data) { return data; }但是什么呢它返回? Truth is that the some_random_func is called by jQuery itself, and AFAIK jQuery doesn't care at all for the return-value of it's success-function. 事实是some_random_func由jQuery本身调用,而AFAIK jQuery完全不关心成功函数的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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