首页 > 解决方案 > 如何添加方法

问题描述

使用其构造函数定义一个名为“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)

我定义了对象及其构造函数,在任务的第二部分变得迟钝,我无法处理方法,有什么想法吗?

标签: javascript

解决方案


您将希望将方法添加到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() {
        ////
    }
}

推荐阅读