在我阅读了很多关于JavaScript原型的帖子之后,在写完第一行代码后的第二天,我不得不问 - 有没有人知道如何制作一个合适的JavaScript原型链?如何将这个非常简单的东西(?)原型化:
然后这个示例代码可以工作:
var södermalm = sweden["södermalm"];
console.info(södermalm.neighbourhood + " is located on the continent " + södermalm.continent);
还有这个:
if (!sweden.neighbourhood) console.warn("Sweden is a country")
答案 0 :(得分:2)
function Continent(nameOfContinent) {
this.continent = nameOfContinent;
}
Continent.prototype.getType = function () { return 'Continent'; }
function Country(nameOfCountry, nameOfContinent) {
Continent.call(this, nameOfContinent);
this.country = nameOfCountry;
}
Country.prototype = new Continent();
Country.prototype.getType = function () { return 'Country'; }
function Region(nameOfRegion, nameOfCountry, nameOfContinent) {
Country.call(this, nameOfCountry, nameOfContinent);
this.region = nameOfRegion;
}
Region.prototype = new Country();
Region.prototype.getType = function () { return 'Region'; }
function City(nameOfCity, nameOfRegion, nameOfCountry, nameOfContinent) {
Region.call(this, nameOfRegion, nameOfCountry, nameOfContinent);
this.city = nameOfCity;
}
City.prototype = new Region();
City.prototype.getType = function () { return 'City'; }
function Neighbourhood(nameOfNeighbourhood, nameOfCity, nameOfRegion, nameOfCountry, nameOfContinent) {
City.call(this, nameOfCity, nameOfRegion, nameOfCountry, nameOfContinent);
this.neighbourHood = nameOfNeighbourhood;
}
Neighbourhood.prototype = new City();
Neighbourhood.prototype.getType = function () { return 'Neighbourhood'; }
let dehradun = new City('dehradun', 'uttarakhand', 'india', 'asia');
let divyaVihar = new Neighbourhood('divya vihar', 'dehradun', 'uttarakhand', 'india', 'asia');
console.log(divyaVihar);
console.log(divyaVihar.neighbourHood + " is located on the continent " + divyaVihar.continent);
console.log(divyaVihar instanceof Neighbourhood);
if(!(dehradun instanceof Neighbourhood)) {
console.log(dehradun.getType())
}