prototypeの使い方
はじめに
javascriptの属性にprototypeと言うものがある.いまいち使い方が良くわからないので,色々試してみた.なお,実行結果はFirebird1.5.0.1で確認している.
インスタンス毎にメソッドを追加
まずクラスBird
を定義してインスタンスを二つostrich
とpenguin
を作った.javascriptの場合,インスタンス単位に独自のメソッドを定義できるので,インスタンスostrich
にメソッドrun
を付け加えてみた.インスタンスpenguin
にはメソッドrun
はない.
以下ののsam.htmlをFirefoxで開くと,JavaScriptコンソールに以下のエラーを表示する.メソッドrun
を定義しているのはインスタンスostrich
のみであり,同じクラスからできていてもインスタンスpenguin
には同名のメソッドが存在しないためである.
penguin.run(); エラー: penguin.run is not a function
<!-- sam.html -->
<html>
<body>
<script type="text/javascript">
function Bird(name){
this.name=name;
}
var ostrich=new Bird("ダチョウ");
var penguin=new Bird("ペンギン");
ostrich.run=function(){ //インスタンス`ostrich`にのみメソッド`run`を定義
document.write(this.name+"は速く走るぜ!<br/>");
}
ostrich.run();
penguin.run(); //エラー: penguin.run() is not a function
</script>
</body>
</html>
これは,インスタンスpenguin
にメソッドを定義しても同じである.インスタンスpenguin
にメソッドswim
を定義してみた.この場合はインスタンスostrich
はメソッドswim
を持っていないため,エラーになる.
<!-- sam.html-->
<html>
<body>
<script type="text/javascript">
function Bird(name){
this.name=name;
}
var ostrich=new Bird("ダチョウ");
var penguin=new Bird("ペンギン");
ostrich.run=function(){
document.write(this.name+"は速く走るぜ!<br/>");
}
ostrich.run();
// penguin.run(); エラー: penguin.run is not a function
penguin.swim=function(){
document.write(this.name+"は速く泳ぐぜ!<br/>");
}
ostrich.swim(); //エラー: ostrich.swim is not a function
penguin.swim();
</script>
</body>
</html>
prototype属性を使う
prototype属性にメソッドを追加することで,すでに生成したインスタンスも含め,新しいメソッドを追加できる.クラスBird
の属性prototype
にメソッドflap
を付け加えると,それ以前に作成していたインスタンスostrich
とpenguin
でもメソッドflap
が使えるようになる.
<!-- sam.html -->
<html>
<body>
<script type="text/javascript">
function Bird(name){
this.name=name;
}
var ostrich=new Bird("ダチョウ");
var penguin=new Bird("ペンギン");
ostrich.run=function(){
document.write(this.name+"は速く走るぜ!<br/>");
}
ostrich.run();
// penguin.run(); エラー: penguin.run is not a function
penguin.swim=function(){
document.write(this.name+"は速く泳ぐぜ!<br/>");
}
// ostrich.swim(); エラー: ostrich.swim is not a function
penguin.swim();
Bird.prototype.flap=function(){ //属性prototypeにメソッドflapを追加
document.write("羽ばたくぜ.でも飛べないのさ.だって"+this.name+"だから<br/>");
}
ostrich.flap(); //ostrichもメソッドflapが使える
penguin.flap(); //penguinもメソッドflapが使える
</script>
</body>
</html>
javascriptがメソッドを以下の順番で探すためである.
- インスタンスの同名メソッド
- クラスのprototype属性から同名のメソッド
ちなみに,ostrich.prototype.flap
やBird.flap
はエラーとなる.
ostrich.prototype.flap=function(){
document.write("羽ばたくぜ.でも飛べないのさ.だって"+this.name+"だから<br/>");
}
エラー: ostrich.prototype has no properties
Bird.flap=function(){
document.write("羽ばたくぜ.でも飛べないのさ.だって"+this.name+"だから<br/>");
}
ostrich.flap();
エラー: ostrich.flap is not a function