Typescript 中類的繼承

Typescript中類的定義與繼承與後端開發語言java/C#等很是像,實現起來很是方便,並且代碼便於閱讀。java

用Typescript寫較大項目時是很是有優點的。後端

/**
 * BaseClass
 */
class BaseClass {
    constructor(name:string,age:number) {
        this.name=name;
        this.age=age;
    }
    
    name:string;
    age:number;
    
    sayName():void{
        console.log(this.name);
    }
}

/**
 * SubClass
 */
class SubClass extends BaseClass {
    constructor(name:string,age:number,job:string    ) {
        super(name,age);
        this.job=job;
    }
    job:string;
    
    sayJob():void{
        console.log(this.job);
    }
    
}

var subClass=new SubClass('張三',18,'Coder');
subClass.sayJob();
subClass.sayName();
console.log(subClass);

編譯後生成的純原生Javascript,也是很是優雅的。this

var __extends = (this && 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 __();
};
/**
 * BaseClass
 */
var BaseClass = (function () {
    function BaseClass(name, age) {
        this.name = name;
        this.age = age;
    }
    BaseClass.prototype.sayName = function () {
        console.log(this.name);
    };
    return BaseClass;
})();
/**
 * SubClass
 */
var SubClass = (function (_super) {
    __extends(SubClass, _super);
    function SubClass(name, age, job) {
        _super.call(this, name, age);
        this.job = job;
    }
    SubClass.prototype.sayJob = function () {
        console.log(this.job);
    };
    return SubClass;
})(BaseClass);
var subClass = new SubClass('張三', 18, 'Coder');
subClass.sayJob();
subClass.sayName();
console.log(subClass);
相關文章
相關標籤/搜索