从数组调用函数时,'this'范围会发生变化

问题描述 投票:0回答:1

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

每个函数都返回一个Promise,它实际上包含一个Observable,我正在绘制一些数据并将其推送到相应的数据数组。调用每个单独的函数工作正常,但是当我试图从函数数组(基于事件的调用)调用它们时,“this”关键字指的是函数数组而不是类。

这是代码:

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)

谢谢。

javascript angular typescript
1个回答
0
投票

由@ConnorsFan和@Pointy给出的答案。

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

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

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.