source code:
// ポリモーフィズムとダイナミックバインディング
// 犬
function Dog(){
// 鳴くメソッド
this.say = function(){
return "bow!";
};
}
// 猫
function Cat(){
// 鳴くメソッド
this.say = function(){
return "meow";
};
}
function createAnimal(){
// ランダムでDogかCatのオブジェクトを返す
switch(Math.floor(Math.random() * 2)){
case 0: return new Dog();
case 1: return new Cat();
}
}
function sampleAnimal(){
var animals = [
new Dog(), // 犬
new Cat(), // 猫
createAnimal(), // 実行してみるまでわからない
createAnimal(), // 実行してみるまでわからない
createAnimal() // 実行してみるまでわからない
];
for(var i=0; i<animals.length; i++){
// 犬か猫が鳴く
print(i + "=" + animals[i].say());
}
}