JavaScriptの継承できるクラスの書き方
インスタンス変数を参照したいときは普通に this 、自クラスや親クラスのメソッドを呼び出したいときは $this を使う。
特殊なことはしていないんだけど、変数名を工夫したら何か分かりやすくなった。
// 継承関数 var extend = function(Klass, SuperKlass) { var F = function() {}; F.prototype = SuperKlass.prototype; Klass.prototype = new F(); Klass.prototype.superclass = SuperKlass.prototype; return Klass.prototype; }; var ClassA = (function() { var ClassA = function() { this.initialize.apply(this, arguments); }, $this = extend(ClassA, Object); $this.initialize = function() { this.value = "A"; }; $this.hoge = function() { console.log("ClassA.hoge!"); $this.fuga.call(this); // fuga.call(this); でもOK }; var fuga = $this.fuga = function() { console.log("ClassA.fuga! this.value=" + this.value); }; return ClassA; }()); var ClassB = (function() { var ClassB = function() { this.initialize.apply(this, arguments); }, $this = extend(ClassB, ClassA); $this.initialize = function() { this.value = "B"; }; $this.hoge = function() { console.log("ClassB.hoge!"); $this.superclass.hoge.call(this); }; $this.fuga = function() { console.log("ClassB.fuga! this.value=" + this.value); $this.superclass.fuga.call(this); }; return ClassB; }()); var ClassC = (function() { var ClassC = function() { this.initialize.apply(this, arguments); }, $this = extend(ClassC, ClassB); $this.initialize = function() { $this.superclass.initialize(this, arguments); this.value = "C"; }; $this.hoge = function() { console.log("ClassC.hoge!"); $this.superclass.hoge.call(this); }; return ClassC; }()); var a = new ClassA(); var b = new ClassB(); var c = new ClassC(); c.hoge(); // ClassC.hoge -> ClassB.hoge -> ClassA.hoge -> ClassA.fuga と呼ばれる console.log("----------------------------------------"); c.fuga(); // ClassB.fuga -> ClassA.fuga と呼ばれる console.log("----------------------------------------"); console.log("* overwrite ClassB.fuga"); b.__proto__.fuga = function() { console.log("piyopiyo"); }; c.fuga(); // 上書きされた ClassB.fuga が呼ばれる