クラス継承もどき
JavaScriptで継承すると Class.prototype = new SuperClass; とした後に Class.prototype = {}; とした途端何もかも駄目になってしまう件(当たり前)プロトタイプチェーンを維持しながらどうにかしようと試行錯誤したところ無理という結論に達したもののその過程で以下のようなものが生成されたのでメモ。
副産物その1
function extend(superclass, constructor) { var f = function(){}; var s = superclass.prototype, f.prototype = s; var p = constructor.prototype = new f; p.__super__ = s; p.constructor = constructor; return constructor; }; Super = function(){}; Super.prototype.foo = "Foo"; Sub = extend(Super, function() { // スーパークラスのコンストラクター呼び出し this.__super__.constructor(); }); Sub.prototype.bar = "Bar"; sub = new Sub(); sub.foo; // Foo sub.bar; // Bar Super.prototype.foo = "Hoge"; sub.foo; // Hoge
副産物その2
Foo = function(){}; (fucntion(Class) { Class.foo = 〜 Class.bar = 〜 })(Foo.prototype); Foo = function(){}; with({ Class : Foo.prototype }) { Class.foo = 〜 Class.bar = 〜 }; 上と下は等価。