JavaScriptでオブジェクト指向しよう4・継承(2)
<SCRIPT LANGUAGE="JavaScript"> <!-- function main(){ no=new Array(); //オブジェクトを入れる配列 cnt=0; //カウンタ no[0]=new wizard("Will", 18, 1, 90); //ウィル 18歳 男 魔力90 no[1]=new soldier("Sophia", 16, 2, 100); //ソフィア 16歳 女 力100 no[2]=new soldier("Dilt", 19, 1, 50); //ディルト様 19歳 男 力50 no[3]=new wizard("Cailtag", 23, 1, 120); //カイル 23歳 男 魔力120 no[4]=new wizard("Lute", 23, 1, 70); //リュート 23歳 男 魔力70 for(cnt in no){ //配列noいっぱいまでループ document.write(no[cnt].stts(no[cnt])); } } //*********** charaクラス ************************************* function chara(name, age, sex_id){ //コンストラクタ(もどき) this.name=name; //名前 this.age=age; //年齢 this.sex_id=sex_id; //性別ID this.sex=chara_sex; //性別 ////// メンバ関数(メソッド) sex() ////// 性別IDから該当する性別(文字列)を返す function chara_sex(id){ str=""; switch(id){ case 1: str="Male"; //性別ID=1 男性 break; case 2: str="Female"; //性別ID=2 女性 break; } return str; } } //*********** wizardクラス ************************************* function wizard(name, age, sex_id, mp){ //子クラスのコンストラクタ(もどき) c=new chara(name, age, sex_id); extnds(this, c); this.mp=mp; //魔力 this.stts=wizard_stts; //ステータス表示 ////// メンバ関数(メソッド) stts() ////// 名前、年齢、性別、魔力を文字列で返す function wizard_stts(obj){ str="Name: "+ obj.name +" <BR>"; str=str + "Age: "+ obj.age +" <BR>"; str=str + "Sex: "+ obj.sex(obj.sex_id) +" <BR>"; str=str + "MagicPower: "+ obj.mp; str=str + "<BR><BR>"; return str; } } //*********** soldierクラス ************************************ function soldier(name, age, sex_id, pw){//子クラスのコンストラクタ(もどき) c=new chara(name, age, sex_id); extnds(this, c); this.pw=pw; //力 this.stts=soldier_stts; //ステータス表示 ////// メンバ関数(メソッド) stts() ////// 名前、年齢、性別、力を文字列で返す function soldier_stts(obj){ str="Name: "+ obj.name +" <BR>"; str=str + "Age: "+ obj.age +" <BR>"; str=str + "Sex: "+ obj.sex(obj.sex_id) +" <BR>"; str=str + "Power: "+ obj.pw; str=str + "<BR><BR>"; return str; } } //*********** 継承関数 extnds() ********************************** // 親クラスのメンバを子クラスにコピーする。 //****************************************************************** function extnds(subclass, superclass){ for(propa in superclass){ subclass[propa]=superclass[propa]; } } //--> </SCRIPT> |