javascript - 如何添加方法
问题描述
使用其构造函数定义一个名为“CityMap”的新对象,该对象可以用“new”实例化。构造函数将一个参数作为字符串 - 这个城市列表及其纬度和经度(FE: "Nashville, TN", 36.17, -86.78; "New York, NY", 40.71, -74.00;)。这个“CityMap”对象应该有以下方法:!!!!!!根据调用者的要求,从列表中返回最北端、最东端、最南端或最西端城市的名称。!!!!!!
function CityMaps(str) {
[this.city, this.abbreviation, this.latitude, this.longitude] = str.split(",")
}
function CityMap(str) {
this.list = [];
str.split(";").forEach(row => {
this.list.push(new CityMaps(row));
});
}
var cityMap = new CityMap("Nashville, TN, 36.17, -86.78;New York, NY, 40.71, -74.00;Atlanta, GA, 33.75, -84.39;Memphis, TN, 35.15, -90.05")
console.log(cityMap.list)
我定义了对象及其构造函数,在任务的第二部分变得迟钝,我无法处理方法,有什么想法吗?
解决方案
您将希望将方法添加到prototype
您的“类”中,如下所示:
function CityMap(str) {
this.list = str.split(';').map(x => new CityMaps(x));
}
CityMap.prototype.getNorthMostName = function() {
// Loop through `this.list` and find the highest item, then return its name.
}
如果您想使用更现代的 JavaScript,那么您可以使用实际的类并为其提供方法。
class CityMap{
constructor() {
////
}
getNorthMostName() {
////
}
}
推荐阅读
- javascript - XPages CSJS 被执行,而 SSJS 不被执行
- bokeh - 可以像 Pandas DataFrame 一样一次性绘制 Bokeh ColumnDataSource 吗?
- python - 'numpy.ndarray' 对象在 Ipython 控制台中不可调用
- ssl - Mosquitto SSL 证书验证失败
- windows - 通过 CLI 从 Admin CMD 执行文件
- javascript - 在没有angularfire的情况下以角度6初始化firebase
- typescript - 打字稿:使用条件映射键时获得正确的推理类型
- c++ - C ++我希望 fscanf 忽略换行符而不是其他空白字符
- python - 有什么好方法可以将 Spark RDD 的内容读入 Dask 结构
- java - Spring MVC @PathVariable 如何接收带有多个'/'的参数?