JavaScriptでオブジェクト指向しよう2・クラス
<SCRIPT LANGUAGE="JavaScript"> <!-- function main(){ no=new Array(); //オブジェクトを入れる配列 cnt=0; //カウンタ no[0]=new chara("Will", 18, 1); //ウィル 18歳 男 no[1]=new chara("Sophia", 16, 2); //ソフィア 16歳 女 no[2]=new chara("Dilt", 19, 1); //ディルト様 19歳 男 no[3]=new chara("Cailtag", 23, 1); //カイル 23歳 男 no[4]=new chara("Lute", 23, 1); //リュート 23歳 男 for(cnt in no){ //配列noいっぱいまでループ document.write(no[cnt].name +" "); //名前を表示 document.write(no[cnt].age +" "); //年齢を表示 document.write(no[cnt].sex(no[cnt].sex_id) +"<BR>"); //性別を表示 } } ////////// 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; } } //--> </SCRIPT> |