foreach中的角调用函数

CS_*_*ent 2 javascript foreach angularjs angular

在我的组件中,有一个foreach循环,当选择一个客户端时会触发该循环。在此循环中,我必须在同一组件中调用一个函数。

为此,我必须使用this.functionName()来调用该函数。但是显然,这在foreach循环内将不起作用,因为“ this”不再是组件本身。

有人对此有解决方案吗?

this.clientService.selectedClient.forEach(function(client) {
    this.getIntake(); // not working
});
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

使用箭头功能

this.clientService.selectedClient.forEach((client) => {
    this.getIntake(); // not working
});
Run Code Online (Sandbox Code Playgroud)

否则this将不会指向本地类实例

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  • 我认为`.bind(this)`也可以 (3认同)