如何将函数绑定到对象?

How to bind function to object?

完整代码为:

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

如果您有一个 A 实例 (我们称它为 a),并希望调用 get 到 return 该实例的 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 逻辑 应用于 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

(On the TypeScript playground)