完整代码是:
export interface IButton {
click: Function;
settings?: IButtonSettings;
}
abstract class Button implements IButton {
click() {}
}
class ButtonReset extends Button {
super()
}
组件为:
export class ButtonsComponent {
private a = "Message";
constructor() {
let btn = new ButtonReset();
btn.click = this.alert;
btn.click(); // Here I want to get console.log(this.a);
}
public alert() {
console.log(this.a);
}
}
为什么我不能将方法alert()
绑定到实例new ButtonReset();
才能调用它?
更简单的示例:
class A {
public message = "message 1";
public b: any;
}
class B {
public message = "message";
c() {
console.log(this.message);
}
}
let instanceA = new A();
let instanceB = new B();
instanceA.b = instanceB.c;
instanceA.b();
我需要获取message
而不是message 1
答案 0 :(得分:2)
如果您的实例为A
(我们将其命名为a
),并希望调用get
返回该实例的items
,那么您将使用bind
创建一个绑定函数以分配给b.get
:
b.get = a.get.bind(a);
JavaScript示例:
class A {
constructor() {
this.items = [];
}
get() {
return this.items;
}
}
class B {
}
const a = new A();
const b = new B();
b.get = a.get.bind(a);
console.log(b.get()); // `[]`, from `a.items`
但是,如果您希望将A.prototype.get
的 logic 应用于b
实例(因此它将得到b.items
),则:
b.get = A.prototype.get;
JavaScript示例:
class A {
constructor() {
this.items = [];
}
get() {
return this.items;
}
}
class B {
constructor() {
this.items = 42;
}
}
const b = new B();
b.get = A.prototype.get;
console.log(b.get()); // `42`, because `b.items` is `42`
在两种情况下,您都需要为b
提供一个类型,该类型表示现在具有一种get
方法,例如像这样:
interface BPlus extends B {
get(): any;
}
您可能还需要具有该类型的新标识符:
const bp = <BPlus>b; // Not true yet...
bp.get = a.get.bind(a); // Now it is