DRYな備忘録

Don't Repeat Yourself.

TypeScriptのthisとメソッドのoverrideについてメモ

  • 親クラスで定義したメソッドa
  • 親クラスで定義したaを呼ぶメソッドcall_a
  • 子クラスでオーバーライドしたa
  • 子クラスのインスタンスcall_aするとどっちが呼ばれる?
module My {
    export class Super {
        a() {
            console.log("ここはスーパーなa");
        }
        call_a() {
            // ここで呼ばれるのはSuper.aかSub.aか
            this.a();
        }
    }
    export class Sub extends Super {
        constructor(){
            super();
        }
        a() {
            console.log("ここはサブなa");
        }
    }
}

var s = new My.Sub();
s.call_a();

結果

% tsc sample.ts
% node sample.js
ここはサブなa

まあoverrideなんだから当たり前か。ちなみにSuper.aを呼びたかったらsuperキーワード使う

--- sample.ts   2014-05-29 12:32:31.000000000 +0900
+++ sample.2.ts 2014-05-29 12:37:19.000000000 +0900
@@ -14,6 +14,8 @@
         }
         a() {
             console.log("ここはサブなa");
+            // 明示的に
+            super.a();
         }
     }
 }

参考までにコンパイルされたjsは

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var My;
(function (My) {
    var Super = (function () {
        function Super() {
        }
        Super.prototype.a = function () {
            console.log("ここはスーパーなa");
        };
        Super.prototype.call_a = function () {
            // ここで呼ばれるのはSuper.aかSub.aか
            this.a();
        };
        return Super;
    })();
    My.Super = Super;
    var Sub = (function (_super) {
        __extends(Sub, _super);
        function Sub() {
            _super.call(this);
        }
        Sub.prototype.a = function () {
            console.log("ここはサブなa");

            // 明示的に
            _super.prototype.a.call(this);
        };
        return Sub;
    })(Super);
    My.Sub = Sub;
})(My || (My = {}));

var s = new My.Sub();
s.call_a();