1.接口
防止多继承出错代码复杂混乱,运用接口
//人 狼 狼人:人,狼
class Person{
name:string;
}
//接口
interface IWolf{
attack();
}
class WolfMan extends Person implements IWolf{//只继承Person 狼是额外接口
attack(){//必须实现接口里的方法
}
}
2.属性寄存器
对一个属性进行手动实现
//属性寄存器
class Person{
_hp:number = 100;
//取值
get hp(){
return this._hp;
}
//赋值
set hp(value){
if(value < 0){
this._hp = 0;
}
else{
this._hp = value;
}
}
}
let a = new Person();
a.hp-=180;
document.write(a.hp + "");
3.命名空间
类命名相同时的解决方法
namespace aa{
export class Person{ //想在外界调用就需要加export
name:string;
}
}
namespace bb{
export class Person{
//...
}
}
//调用
let person1 = new aa.Person();//实例化aa的Person
let person2 = new bb.Person();
4.泛型
function add(num:any):any{
if(typeof(num) == "number"){
num++;
return num;
}
return num;
}
可能造成传进来一个number传出去一个string
使用泛型:
function add<T>(num:T):T{ //T指任意类型
if(typeof num == "number"){
num++;
return num;
}
return num;
}
//调用
document.write(add<number>(3)+ "");//声明传进来的是个number
传进去的是number类型,传出来的也是number类型,容易得到返回值类型