2017-07-14 73 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' –