studye / typescript

타입스크립트는 자바스크립트랑 다른 언어인가요?
7 stars 0 forks source link

[typescript - 2.1] Use returned values from super calls as ‘this’ #34

Open denzels opened 7 years ago

denzels commented 7 years ago

ES2015 와 동일하게 동작하도록 super() 의 반환값이 있는 경우 이를 받아서 처리할 수 있도록 변환 코드가 변경 됨.

class Base {
    x: number;
    constructor() {
        return {
            x: 1,
        };
    }
}

class Derived extends Base {
    constructor() {
        super();
        console.log( this.x );
        this.x = 2;
    }
}
let n = new Derived();

변환 후

Typescripte 2.0

var Base = (function () {
    function Base() {
        return {
            x: 1
        };
    }
    return Base;
}());
var Derived = (function (_super) {
    __extends(Derived, _super);
    function Derived() {
        _super.call(this);
        console.log(this.x); // undefined
        this.x = 2;            
    }
    return Derived;
}(Base));
var n = new Derived();

Typescripte 2.1

var Base = (function () {
    function Base() {
        return {
            x: 1
        };
    }
    return Base;
}());
var Derived = (function (_super) {
    __extends(Derived, _super);
    function Derived() {
        var _this = _super.call(this) || this;           // <== 요기 
        console.log(_this.x); // 1
        _this.x = 2;
        return _this;                                               // <== _this를 반환하고 있음.
    }
    return Derived;
}(Base));
var n = new Derived();