javascript:inherit
差分
このページの2つのバージョン間の差分を表示します。
| 次のリビジョン | 前のリビジョン | ||
| javascript:inherit [2008/07/03 09:51] – 外部編集 127.0.0.1 | javascript:inherit [2025/09/10 06:40] (現在) – 削除 nullpon | ||
|---|---|---|---|
| 行 1: | 行 1: | ||
| - | ====== 継承とオーバーライド ====== | ||
| - | ===== 継承 ===== | ||
| - | インスタンスのメソッドを呼び出されたとき、prototypeからメソッドを探すので、インスタンスのコンストラクタが持っている prototype を適当な別のクラスのインスタンスに書き換えれば、その置き換えたクラスのメソッドを全て利用することができる。 | ||
| - | |||
| - | |||
| - | ClassBのprototypeをClassAのインスタンスに置き換えることで、ClassBのインスタンスがClassAのメソッドを呼べるようになる。 | ||
| - | <code javascript> | ||
| - | function ClassA(){ | ||
| - | } | ||
| - | ClassA.prototype.execute = function(){ | ||
| - | window.alert(" | ||
| - | } | ||
| - | |||
| - | function ClassB(){} | ||
| - | ClassB.prototype = new ClassA(); | ||
| - | |||
| - | new ClassA().execute(); | ||
| - | new ClassB().execute(); | ||
| - | </ | ||
| - | |||
| - | ===== オーバーライド ===== | ||
| - | 継承した親クラスのメソッドと同じ名前のメソッドを定義するだけ。 | ||
| - | |||
| - | <code javascript> | ||
| - | function ClassA(){ | ||
| - | this.hoge = " | ||
| - | } | ||
| - | ClassA.prototype.execute = function(){ | ||
| - | window.alert( this.hoge + " | ||
| - | } | ||
| - | |||
| - | function ClassB(){} | ||
| - | ClassB.prototype = new ClassA(); | ||
| - | ClassB.prototype.execute = function(){ | ||
| - | window.alert( this.hoge + " | ||
| - | } | ||
| - | |||
| - | new ClassA().execute(); | ||
| - | new ClassB().execute(); | ||
| - | |||
| - | </ | ||
| - | 実際の処理は次のようになる。オーバーライド前のメソッド呼び出しは | ||
| - | |||
| - | 自分のexecuteメソッドを探す | ||
| - | →見つからないので prototype の execute を探す | ||
| - | →見つからないので prototype の prototype の execute を探す | ||
| - | →見つかったのでexecute実行 | ||
| - | |||
| - | これがオーバーライドによって、 | ||
| - | |||
| - | 自分のexecuteメソッドを探す | ||
| - | →見つからないのでprototype の executeを探す | ||
| - | →見つかったのでexecute実行 | ||
| - | |||
| - | と変化したのである。なお、このような prototype 参照の連鎖を**プロトタイプチェイン**と呼ぶ | ||
| - | |||
| - | ===== 親クラスのメソッドを呼ぶ。 ===== | ||
| - | |||
| - | 親クラスのメソッドを呼び出すにはcallメソッドを使います。 | ||
| - | |||
| - | callメソッドは Functionオブジェクトのメソッドで、第一引数に渡したオブジェクトのメソッドとして自分自身を実行するものです。以下の例では、prototype の execute メソッドを自分自身のメソッドとして実行します。そうしないとClassA.execute で this.hoge が undefined になってしまいます。 | ||
| - | <code javascript> | ||
| - | function ClassC(){} | ||
| - | ClassC.prototype = new ClassA(); | ||
| - | ClassC.prototype.execute = function(){ | ||
| - | this.hoge = " | ||
| - | this.constructor.prototype.execute.call(this , arguments); | ||
| - | } | ||
| - | |||
| - | // Cクラスから親クラスのメソッドを呼ぶAのメソッド と表示される | ||
| - | new ClassC().execute(); | ||
| - | </ | ||
| - | なお、JavaScriptにはsuperキーワードはありませんが、予約語なので変数名などに使用することはできません。 | ||
| - | |||
| - | |||
| - | ===== constructorプロパティ ===== | ||
| - | '' | ||
| - | |||
| - | <code javascript> | ||
| - | new ClassC().constructor; | ||
| - | new ClassC().hasOwnProperty(" | ||
| - | </ | ||
| - | |||
| - | '' | ||
| - | |||
| - | |||
javascript/inherit.1215078716.txt.gz · 最終更新: (外部編集)