関数オブジェクトを使ったクラス作成 - 応用クラスの作成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); }; };
3. プロトタイプでメソッドを定義var Animal = function(name, age) { this.name = name; this.age = age; }; Animal.prototype = { sayName: function() { alert("My name is " + this.name); } };
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(); 継承子クラスの作成 1var Dog = function(name, age) { this.name = name; this.age = age; }; Dog.prototype = new Animal; Dog.prototype.sayAge = function() { alert("My age is " + this.age); }
子クラスのインスタンスを作成・メソッドを利用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); }
prototypeのconstructorプロパティ↑のままではDogクラスのprototypeのconstructorプロパティはAnimalなので、これをDogにする場合は↓のようにする。 Dog.prototype = new Animal; Dog.prototype.constructor = Dog; |
|