es5中構造類的方法
function run(){this.name='張三';
this.age=20;
this.sun=function(){console.log(this.neme+'在運動')}
}
var p= new run()
此時調用p.sun得到張三在運動
也可加在原型鏈上run,prototype.sex='男'
在ts中通過class關鍵字來定義
class Person{
name:string;//前面省略了public關鍵詞
constructor(n:string){
this.name=n
}//構造函數(shù),實例化類的時候觸發(fā)發(fā)方法
run():void{
alert(this.name)
}
}
var p =new Person('張三')
p.run()
得到張三,方法類似雨es6
ts中類的繼承,使用extends和super實現(xiàn)
class Person{
name:string;
constructor(n:string){
this.name=n
}
run():void{
return '$(this.name)在運動'
}
}
class web extends Person{
constructor(name:string){
super(name)
}//初始化父類的構造函數(shù)
}
var p =new web('張三')
p.run()
此時web即可繼承Person的類
類的修飾符
- ts中定義類的屬性時提供了三種修飾符
1、public,公有,在當前類,子類,外部都可以訪問到;
2、protected ,保護類型,在當前類和子類中可以訪問到;
3、private,私有,在當前類中可以訪問到;
如果屬性不加修飾符,默認是公有的public