1.Ts 类中get与set使用意义
class User {
name: string;
age!: number;
phone: number;
gender: string;
constructor(name: string, phone: number, gender: string) {
this.name = name;
this.gender = gender;
this.phone = phone;
}
eat() {
console.log(this.name + '吃饭====!');
}
introduceSelf() {
console.log(
`我的名字叫${this.name},今年${this.age},我的电话是${this.phone}`
);
}
setAge(val: number) {
if (val >= 18 && val < 120) {
this.age = val;
console.log(this.name + '的年龄是' + this.age);
} else {
throw new Error('年龄不合法');
}
}
getAge() {
return this.age;
}
}
const user1 = new User('程序员', 123456789, '男');
const user2 = new User('青年', 123456789, '女');
console.log(user1);
user1.setAge(18);
user1.eat();
console.log(user2);
2.TS中静态成员,方法拦截器
class User2 {
name: string;
age!: number;
phone: number;
gender: string;
constructor(name: string, phone: number, gender: string) {
this.name = name;
this.gender = gender;
this.phone = phone;
}
eat(whose: string, where: string) {
console.log(`${whose},在${where} 吃饭 = =!`);
}
introduceSelf() {
console.log(
`我的名字叫${this.name},今年${this.age},我的电话是${this.phone}`
);
}
setAge(val: number) {
if (val >= 18 && val < 120) {
this.age = val;
console.log(this.name + '的年龄是' + this.age);
} else {
throw new Error('年龄不合法');
}
}
getAge() {
return this.age;
}
}
class StringTrim {
static trim(str: string): string {
return str.replace(/\s+/g, '|');
}
}
const p11 = Object.getOwnPropertyDescriptor(User2.prototype, 'eat');
const p22 = Object.getOwnPropertyDescriptor(User2.prototype, 'eat');
const targetMethod = p11?.value;
p11!.value = function (...args: any[]) {
console.log('----开始前置处理');
args = args.map(item=>{
console.log(item);
if(typeof item === 'string')return StringTrim.trim(item);
return item;
});
targetMethod.apply(this, args);
console.log('后置处理成功----');
};
p11?.value('张 三', '悦 来 饭 店');
console.log(p11);
console.log(p22);
console.log(p22 === p11);