JavaScriptでクラス定義
- 2008/04/23 15:27
- カテゴリー:制作, プログラム
- タグ:JavaScript
書き方が色々あるけど、自分では以下のように書くとします。
/* クラスを定義 */
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function() {
document.write(this.name + ' : ぱくぱく<br />');
};
/* クラスを継承 */
function Dog(name) {
this.name = name;
}
Dog.prototype = new Animal();
Dog.prototype.bark = function() {
document.write(this.name + ' : わんわん<br />');
};
/* クラスを利用 */
pochi = new Dog('ポチ');
pochi.eat();
pochi.bark();
以前から書いている方法。一番見慣れているのでひとまずこれで。
prototype.js
利用時は以下のように書くとします。
/* クラスを定義 */
var Animal = Class.create();
Animal.prototype = {
initialize: function(name) {
this.name = name;
},
eat: function() {
document.write(this.name + ' : ぱくぱく<br />');
}
};
/* クラスを継承 */
var Dog = Class.create();
Dog.prototype = Object.extend(new Animal, {
bark: function() {
document.write(this.name + ' : わんわん<br />');
}
});
/* クラスを利用 */
pochi = new Dog('ポチ');
pochi.eat();
pochi.bark();
クラスの継承は
子クラス.prototype = Object.extend(new 親クラス, { ~ });
としてみる。
class 子クラス extends 親クラス { ~ }
の書き方が(言語を問わなければ)一番見慣れているので、近い書き方にしてみた。
今後変えていくかもしれないけど。