【JS】Expanding functionality through prototype

ファンクションの追加をprototypeを使ってやってみる

by tea4two

JavaScript

var speak = function(saywhat) {
    console.log(saywhat);    
}

var Dog = function() {
    var name, breed;
}

var Cat = function() {
    var name, breed;
}

//ここでDogオブジェクトにspeakファンクションをprototypeを用いてくっつける
Dog.prototype.wanwan = speak;
Cat.prototype.meow = speak;

firstDog = new Dog;
firstDog.name = 'フレッド';
firstDog.breed = 'ラブラドールレトリバー';
firstDog.wanwan('(U^ω^)わんわんお!');

firstCat = new Cat;
firstCat.name = 'にゃんた';
firstCat.breed = '雑種';
firstCat.meow('にゃんにゃんこ!');