首页 > 解决方案 > 从孩子访问父母/祖父母/等财产(不是继承)

问题描述

只是想知道以下情况的最佳实践是什么,我进行了搜索,但似乎只得到了引用父/子继承的结果,而这不是,我想不出另一种说法!

假设我有以下简化的示例对象:

现在,如果我想计算特定地点的日出/日落时间,我需要日期、纬度和经度。就目前而言,我的站点对象具有以下(伪代码)功能:

var Site = function() {
    var lat;
    var lng;

    var calculateSunriseSunset = function(date) {
        // do calculation with lat, lng and date
        return result;
    }
}

例如,我可能会这样调用该函数:

site.calculateSunriseSunset(quote.get('date')); // site here is a reference to a specific site object 

其中 'quote' 是对父 Quote 对象的全局引用。对我来说,这很丑陋,而且似乎是不好的做法(循环引用?耦合?)。

但是,我能想到的另外两个选择是:

有没有更好的方法可以做到这一点,我错过了?

谢谢

编辑

1)为了澄清我所说的“全局参考”的意思,我只是说我使用了以下代码:

var quote = new Quote();

其中 quote 是在全局命名空间中定义的,并且可以从任何地方调用。


2) 'calculateSunriseSunset' 函数从另一个对象调用,一个'Map' 对象,它处理与显示给用户的地图有关的所有事情。它看起来有点像这样(为了清楚起见,做了很多简化):

var Map = function() {
    var sites; // list of sites loaded from the server
    var leafletMap; // reference to the [Leaflet][1] map object used to do the 'heavy lifting'
    var root = this;

    showSites = function() {
        var siteLayer = L.geoJson(sites, {
            onEachFeature: function (feature, layer) {
                layer.on('click', function (e) {
                    root.openPopup(e.target.feature);
                });
             },
        }).addTo(leafletMap);
    }

    this.openPopup = function(site) {
        var popup = L.popup().setContent(site.calculateSunriseSunset(quote.get('date'))).openOn(leafletMap);
    }
}

标签: javascriptoopparent-child

解决方案


推荐阅读