注: bind方法会让代码更简短,但是可阅读性不好
class A {
public name: string = "张三"
public sayName() {
console.log(this.name)
}
}
class B {
public name: string = "李四"
// 函数作为参数
public heSay(handle: () => void) {
handle()
}
public sayName() {
console.log(this.name)
}
// example1
public test() {
let peopleA: A = new A();
this.heSay(peopleA.sayName.bind(peopleA)) //"张三"
}
// example2
// public test(){
// let peopleA:A = new A();
// this.heSay(peopleA.sayName.bind(peopleA)) //"李四"
// }
}
let peopleB: B = new B();
peopleB.test();