javascript - 从孩子访问父母/祖父母/等财产(不是继承)
问题描述
只是想知道以下情况的最佳实践是什么,我进行了搜索,但似乎只得到了引用父/子继承的结果,而这不是,我想不出另一种说法!
假设我有以下简化的示例对象:
- 地图对象(见下面的编辑)
- Quote 对象,其中包含:
- 日期对象,
- Route 对象,其中包含:
- 航点数组,每个包含:
- Site 对象,其中包含以下属性:
- 纬度
- 经度
- Site 对象,其中包含以下属性:
- 航点数组,每个包含:
现在,如果我想计算特定地点的日出/日落时间,我需要日期、纬度和经度。就目前而言,我的站点对象具有以下(伪代码)功能:
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 对象的全局引用。对我来说,这很丑陋,而且似乎是不好的做法(循环引用?耦合?)。
但是,我能想到的另外两个选择是:
- 将 calculateSunriseSunset 移动到 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);
}
}
解决方案
推荐阅读
- excel - 运行时错误 1004 使用 vba 的 vlookup 中的应用程序定义或对象定义错误
- reactjs - 如果 initialValue 更改,则更新 antd 表单
- java - 如何使用内部变量制作 String.format 标志
- java - 如何将数组长度设置为变量,Java
- modbus - 配置 Modbus 从站自动增量
- database - 无法连接到 PgBouncer 管理控制台
- html - 悬停效果适用于页面中的所有锚标签
- python - sns.scatter plot python,指定大小
- django - Apache2 上的 Django 应用程序禁止 403 响应
- ios - 在不同部分的单元格中添加多个复选标记并将其状态保存在swift ios中