1.类声明和使用
class Perpon {
name : string = "小赵";
age : number = 24;
isShow :boolean = true;
// 构造函数
constructor(name:string,age:number,isShow:boolean){
this.name = name;
this.age = age;
this.isShow = isShow
}
puperyInfo(){
if (this.isShow) {
console.log(`我叫${this.name},我是一个女孩,我今年${this.age}`)
}else{
console.log(`我叫${this.name},我是一个人男孩,我今年${this.age}`)
}
}
}
const perpon :Perpon = new Perpon("小范",25,true);
console.log(perpon.puperyInfo())//我叫小范,我是一个女孩,我今年25
// const perpon:Perpon = new Perpon()//这个是构造函数没有接参,
// console.log(`我叫${perpon.name},我今年${perpon.age}`)
封装
class Person{
public name : string = "小赵";
private _age : number = 24;
isMale : boolean = true;
// 构造方法
constructor(name:string,age:number,isMale:boolean){
this.name = name;
this._age = age;
this.isMale = isMale;
}
pupery(){
if(this.isMale){
console.log(`我叫${this.name},我是一个女孩,我今年${this.age}`)
}else{
console.log(`我叫${this.name},我是一个人男孩,我今年${this.age}`)
}
}
get age() : number{
return this._age
}
set age(age:number){
this._age = age
}
}
const person : Person = new Person("小范",25,false)
console.log('实际是访问的get方法', person.age.toString())