Typescript 中类的继承

时间:2023-04-02 13:55:02

Typescript中类的定义与继承与后端开发语言java/C#等非常像,实现起来非常方便,而且代码便于阅读。

用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,也是非常优雅的。

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);