関数オブジェクトを使ったクラス作成 - 応用

クラスの作成

1. 空のコンストラクタ

 var Animal = function() {};
  • 関数オブジェクトをクラスのコンストラクタに見立てる。

2. コンストラクタでメソッドやフィールドを定義

 var Animal = function(name, age) {
     this.name = name;
     this.age  = age;
      
     this.sayName  = function() { 
         alert("My name is " + this.name);
     };
 };
  • thisを使ってクラスのプロパティにアクセスする。
  • ただし、この方法はインスタンス生成ごとにメソッドを定義する事になり、メモリ効率が悪い。これを避けるには、↓のようにプロトタイプによるメソッドの定義を行う。

3. プロトタイプでメソッドを定義

 var Animal = function(name, age) {
    this.name = name;
    this.age  = age;
 };
 Animal.prototype = {
     sayName: function() {
         alert("My name is " + this.name);
     }
 };
プロトタイプ汚染について
この方法でArrayのような組込みクラスを拡張する事が可能だが、安易に拡張するとfor inでオブジェクトのプロパティを列挙すると拡張したプロパティ(メソッド)と元のプロパティ(メソッド)が混ざってしまう(プロトタイプ汚染)ので注意が必要。

4. プロパティもプロトタイプに乗せたい場合

 var Animal = function(name, age) {
     this.init.apply(this, arguments);
 };
 Animal.prototype.init = function (name, age) {
     this.name = name;
     this.age  = age;
  
     sayName: function() {
         alert("My name is " + this.name);
     }
 };

インスタンスを生成・メソッドを利用

 var a = new Animal("Taro", 10);
 a.sayName();

継承

子クラスの作成 1

 var Dog = function(name, age) {
     this.name = name;
     this.age  = age;
 };
 Dog.prototype = new Animal;
 Dog.prototype.sayAge = function() {
     alert("My age is " + this.age);
 }
  • Dog.prototype = new Animal で継承を実現している。
  • Dog.prototype.sayAge = function()... でメソッドを子クラスに追加している。

子クラスのインスタンスを作成・メソッドを利用

 var d = new Dog("Jiro", 5);
 d.sayAge();

子クラスの作成 2(子クラスのコンストラクタで親クラスのコンストラクタを利用)

 var Dog = function(name, age) {
      Animal.call(this, name, age);
 };
 Dog.prototype = new Animal;
 Dog.prototype.sayAge = function() {
     alert("My age is " + this.age);
 }
  • 子クラスの作成 1ではコンストラクタ内での処理を書き直す必要があるので、call()を使って、子クラスthisに親クラスのコンストラクタメソッドAnimal()を適用して、書き直す手間を省く。
  • call()とは JavaScript/文法/関数/call()とapply()

prototypeのconstructorプロパティ

↑のままではDogクラスのprototypeのconstructorプロパティはAnimalなので、これをDogにする場合は↓のようにする。

 Dog.prototype = new Animal;
 Dog.prototype.constructor = Dog;

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2012-09-18 (火) 07:59:53