从数组调用函数时,“ this”范围发生变化

时间:2019-04-02 13:09:02

标签: javascript angular typescript

为了代码简短,我试图在数组中存储一些类似的函数,然后根据数字键调用正确的函数。

每个函数都返回一个Promise,它实际上包装了一个Observable,我正在处理一些数据并将其推入相应的数据数组。 调用每个单独的函数都可以正常工作,但是当我尝试从functions数组(基于事件的调用)中调用它们时,“ this”关键字引用的是function数组而不是类。

代码如下:

public currentKey = 0;
...
constructor(private api: ApiService) {
  }

  ngOnInit() {
    this.loadTrending(0); //THIS WORKS!
    this.loadNews(0);
    ....
    this.loadingMethods = [this.loadTrending, this.loadNews, this.loadCrowdfunding, this.loadUpcoming]

  }

  loadData(event) {

    this.loadingMethods[this.currentKey](this.offsets[this.currentKey]).then(bool => {
      event.target.complete(); // THIS DOESN'T WORK

    });

  }

 public loadTrending(offset: number): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.api.trending(offset).subscribe(trending => { //'THIS' REFERS HERE TO THE ARRAY
        this.gameLists[this.TRENDING_KEY].push(...trending.list);
        resolve(true);
      });
    });
  }

是否有一种方法可以实现此函数调用,并像往常一样引用该类?

编辑:我已经在使用ECMA6箭头函数,该函数可以遍及我的所有项目,因此我不认为How to access the correct `this` inside a callback?是答案。即使在那里有充分的解释。

错误是:

core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'trending' of undefined
TypeError: Cannot read property 'trending' of undefined
    at news.page.ts:68
    at new ZoneAwarePromise (zone.js:910)

谢谢。

1 个答案:

答案 0 :(得分:0)

@ConnorsFan和@Pointy给出的答案。

需要在我的数组中使用.bind(),因为即使我使用箭头函数,从数组中调用方法通常也会更改“ this”的上下文。

this.loadingMethods = [this.loadTrending.bind(this), ...]

谢谢。

相关问题