如何将功能绑定到对象?

时间:2019-06-28 14:11:26

标签: typescript typescript2.0

完整代码是:

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

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

On the TypeScript playground