class Student{
name: string
age!: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
study(className: string, address: string = '') {
console.log(`${this.name}正在${address}学习${className}课程`)
}
}
const s1: PropertyDescriptor = Object.getOwnPropertyDescriptor(Student.prototype, 'study') as PropertyDescriptor
const newMethod = s1!.value
s1!.value = function(...args: any[]) {
// 前置拦截do sth...
newMethod.apply(this, args)
// 后置拦截do sth...
}
Object.defineProperty(Student.prototype, 'study', s1)
const student2 = new Student('李四', 23)
student2.study('语文')
效果:
Object.getOwnPropertyDescriptor(obj, prop)
作用:返回指定对象上一个自有属性对应的属性描述符(值,是否可写,是否可枚举,是否可配置)
1、obj: 要查询的对象
2、prop:要获取属性描述符的属性名称 string
3、返回值:不存在返回undefined; 存在返回一个对象
- value:该属性的值
- writable:该属性的值是否可被赋值运算符改变(即是否可写) boolean
- enumerable:该属性是否可被枚举 boolean
- configurable:该属性的描述符是否可被改变,以及此属性是否可以从对应对象上被删除 boolean
Object.defineProperty(obj, prop, descriptor)
作用:添加或修改对象的属性
1、obj: 定义属性的对象
2、prop:要定义或修改的属性名称 string
3、descriptor:属性描述符对象