ts中的类和es6中大体相同,
class Parent {private _foo = "foo"; // 私有属性,不能在类的外部访问private foobar = "foobar"; // 公开属性,能在类的外部访问protected protectedBar = "protectedBar"; // 保护属性,可以在子类中访问// 参数属性:构造函数参数加修饰符,能够定义为成员属性constructor(public tua = "tua") {}// 方法也有修饰符// 私有方法,不能在类的外部访问private privateMethod() {console.log(this);}// 公开方法,不能在类的外部访问public publicMethod() {console.log(this);}// 保护方法,可以在子类中访问protected protectedSay() {console.log("protectedSay");}// 存取器:属性方式访问,可添加额外逻辑,控制读写性get foo() {return this._foo;}set foo(val) {this._foo = val;}// 静态方法static isParent(a: any) {return a instanceof Parent;}}
继承,
class ChineseParent extends Parent {constructor(public from = "gd") {super("tuatuatua"); // 调用父类的 constructor}getProtected() {// 获取父类的保护属性console.log(this.protectedBar);// 获取父类的保护方法console.log(this.protectedSay());}}
