JavaScriptでPython風にクラスを定義できるClassyというのを発見した。
まず「<script type="text/javascript" src="classy.js"></script>」しておいて
var Animal = Class.$extend({ __init__ : function(name, age) { this.name = name; this.age = age; this.health = 100; }, die : function() { this.health = 0; }, eat : function(what) { this.health += 5; } });
というようにクラスを定義する。「__init__」って書くだけでワクワクしてくる:-D。エラーは出ないけど,インデントはあった方がいいね。
Animalはベースクラスなので,継承してサブクラスを定義する。
var Tiger = Animal.$extend({ eat : function(animal) { this.$super(animal); animal.die(); } }); var Sheep = Animal.$extend({ __init__ : function(name, age) { this.$super(name, age); this.shorn = false; } });
インスタンスを作ってみよう。
var leo = Tiger("Leo", 3); var molli = Sheep("Molli", 1);
羊のMolliは虎のLeoに食べられてしまいました。
leo.eat(molli);
これで,JavaScriptの開発中もPythonicになれる,かも:-)。