- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- ソース を表示
- JavaScript/OOP/クラスの作り方/オブジェクトリテラルを使ったクラス作成 - 応用 へ行く。
- 1 (2011-07-13 (水) 23:47:15)
- 2 (2011-07-13 (水) 23:47:45)
- 3 (2011-07-14 (木) 20:06:18)
- 4 (2011-07-26 (火) 03:54:58)
- 5 (2012-07-24 (火) 16:58:20)
オブジェクトリテラルを使ったクラス作成 - 詳細
クラスの作成
var Animal = function (name, age) {
var that = {};
that.name = name;
that.age = age;
that.sayName = function () {
alert("My name is " + this.name);
}
return that;
};
Animal()はコンストラクタであり、初期化処理後、オブジェクトリテラル(that)を返す。
インスタンスを作成・メソッドを利用
var a = Animal("Taro", 10);
a.sayName();
オブジェクトリテラルを使ったクラスのメリット
クラス内の変数・関数を隠蔽出来る。この例の場合、thatにageをセットしなければ、ageはプライベート変数になる。
継承
子クラスの作成
var Dog = function (name, age) {
var that = Animal(name, age);
that.sayAge = function () {
alert("My age is " + this.age);
}
return that;
}
thatを(空のオブジェクトリテラルではなく)Animal()で初期化して、Animalの継承を実現している。
子クラスのインスタンスを作成・利用
var d = Dog("Jiro", 5);
d.sayName();
d.sayAge()
- sayName()は親クラスで定義、sayAge()は子クラスで定義されている。