2015-09-27 67 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!'