前篇:TypeScript学习(二)—— 函数es6
js中的类能够看以前写的:new操做符到底干了什么。函数
接下来讲说TypeScript中的class。在TS中class的定义方式和es6中的语法糖class很类似。post
class A {
name:string //声明name是string类型,省略了public
constructor(name:string){
this.name = name
}
run():void { //定义A.prototype上的run方法
console.log(this.name)
}
getName():string{
return this.name
}
setName(name:string):void{
this.name = name
}
}
const a = new A() //没给默认值不传参数会报错
const a = new A('汪汪!') //没给默认值不传参数会报错
a.run() //汪汪!
a.setName('咪咪!')
console.log(a.getName()) //'咪咪'
复制代码
class Animal { //定义父类
name:string
constructor(name:string){
this.name = name
}
sayName():void{
console.log(`i am ${this.name}`)
}
}
class Cat extends Animal{ //定义个继承父类的子类
call:string
constructor(name:string, call:string = 'mimimi!'){ //若是和Animal中构造函数传入的name类型不一样就会报错
super(name) //做用是把this传到父类,调用父类构造函数
this.call = call
}
sayCall():void{
console.log(`我是${this.name},个人叫声是:${this.call}`)
}
}
const cat = new Cat('咪咪', '喵喵')
cat.sayName() //i am 咪咪
cat.sayCall() //我是咪咪,个人叫声是:喵喵
复制代码
public:公有属性,在类里面、子类、类外面均可以访问学习
protected:保护类型,在类里面、子类里面能够访问,在类外部无法访问ui
private:私有属性,在类里面能够访问,子类和类外部没法访问this
若是不写默认为public。(其实只是代码检测会报错,编译成es5后均可以访问获得)es5
//public
class Animal {
public name:string
...
sayName():void{
console.log(`i am ${this.name}`) //类里面能够访问
}
}
class Cat extends Animal{
...
sayCall():void{
console.log(`我是${this.name},个人叫声是:${this.call}`) //子类中能够访问
}
}
const animal = new Animal('dog')
console.log(animal.name) //类外面能够访问
//protected
class Animal {
protected name:string
...
sayName():void{
console.log(`i am ${this.name}`) //类里面能够访问
}
}
class Cat extends Animal{
...
sayCall():void{
console.log(`我是${this.name},个人叫声是:${this.call}`) //子类中能够访问
}
}
const animal = new Animal('dog')
console.log(animal.name) //编译器报错,类外面访问不到
//private
class Animal {
private name:string
...
sayName():void{
console.log(`i am ${this.name}`) //类里面能够访问
}
}
class Cat extends Animal{
...
sayCall():void{
console.log(`我是${this.name},个人叫声是:${this.call}`) //编译器报错,子类中访问不到
}
}
const animal = new Animal('dog')
console.log(animal.name) //编译器报错,类外面访问不到
复制代码
class Animal {
...
static SF():void{ //定义静态方法
console.log(this.SP)
}
static SP:string = '我是静态属性' //定义静态属性,不建议定义静态属性
}
Animal.SF() // =》我是静态属性 静态方法是在类上调用的方法,方法中的this指向Animal自己
console.log(Animal.SP) // =》我是静态属性
复制代码