2017-07-14 2 views
-1

最初のコード行を書き終わった翌日、人々が書いたJavaScriptプロトタイプに関する多くの記事を読んだところ、適切な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") 

答えて

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()) 
 
}

+0

'constructor'はContinent''に設定されていますか? –

+0

はい、一般的にコンストラクタは大陸を指します。これを修正するには、次の行を追加します。 'Child.prototype.constructor = Child' –

関連する問題