2015-09-27 41 views
0

我無法確定在JavaScript中是否正確使用原型/子類。JavaScript中的原型/子類

下面是這個構造函數,我有:

function SentientBeing(homePlanet, language) { 
    this.homePlanet = homePlanet; 
    this.language = language; 
} 

而且我與創建SentientBeing的三個「子」的任務。這是否被認爲是正確的,還是我不正確地做這件事? 在此先感謝。

// TODO: create three subclasses of SentientBeing, one for each 
// species above (Klingon, Human, Romulan). 
function Human() { 
    SentientBeing.call(this, homePlanet, language); 
} 
function Romulan() { 
    SentientBeing.call(this, homePlanet, language); 
} 
function Klingon() { 
    SentientBeing.call(this,homePlanet, language); 
} 

回答

0

這是很難找出來,你要在這裏achive什麼,但我會很快展示如何使用原型:

function SomeClass() { 
    this.a = 'a'; 
    this.b = 'b'; 
} 

// Objects Method 
SomeClass.prototype.methodHello = function(name) { 
    console.log('Hi, ' + name + '!'); 
}; 

// call this way: 
var obj = new SomeClass(); 
obj.methodHello('Jose'); // => 'Hi, Jose!' 

// Static Method 
SomeClass.staticHello = function(name) { 
    console.log('Hello, ' + name + '!'); 
}; 

// call this way: 
SomeClass.staticHello('Herku'); // => 'Hello, Herku!'