【问题标题】:Callback function will not call other member functions of its class回调函数不会调用其类的其他成员函数
【发布时间】:2019-01-08 19:22:49
【问题描述】:

我的回调函数不会调用同一个类实例的另一个成员函数

在 Angular 中使用 typescript,我有一个类,它定义了一个公共成员函数 myCallback(),它作为回调函数传递给 ngrx 商店订阅,并异步调用。 myCallback() 函数尝试调用其同一个类实例的另一个成员函数this.funcA(),但失败并出现funcA() 未定义的错误。

myCallback() 可以调用其同一个类实例的成员属性this.prop,并且可以调用不是同一个类的成员的函数,例如funcB()

我怀疑这与this 上下文变化有关。但是我可以使用this 成功调用属性,但不能调用函数??

这是怎么回事,我不明白什么?

export class MyClass implements OnInit
{
  public prop:boolean;
  private sub:Subscriber;
  constructor(public storeY:Store<fromY.FeatureState>){}

  ngOnInit(){
    this.sub = new Subscriber(this.storeY);
    this.sub.myCallback = this.myCallback;
    this.sub.subscribe();
} 

  public myCallback()
  {
    this.prop=true; //works
    this.funcA(); //does not work, funcA not defined
    funcB(); //works
  }

  public funcA()
  {}
} //end class

funcB(){}

订户类的缩写

export class Subscriber  {
  public myCallback: () => void;
  constructor(public storeY:Store<fromY.FeatureState>) 
  { }

  public subscribe() //called in external ngOnInit 
  {
    this.storeY.select(state => state.myData)
    .pipe()
    .subscribe((data:object) =>{
      this.myCallback(); //calling callback
    }
  }) 
} 

【问题讨论】:

  • 你试过胖箭头函数吗:myCallback = () => {}
  • 因为 this 会根据范围而变化,因此 this.funcA() 在您直接从 ngOnInit 调用函数 myCallback 时定义(例如),但在您调用时它将未定义它来自回调中的其他类

标签: angular typescript


【解决方案1】:

这是一个上下文问题。

通过写作

 this.sub.myCallback = this.myCallback;

您更改了调用者的上下文:this 关键字现在引用了其他内容,在本例中它是 sub 变量。

使用bind 将正确的上下文绑定到您的元素:

this.sub.myCallback = this.myCallback.bind(this)

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多