javascript - 调用javascript方法变量丢失'this'
问题描述
我创建了一个指向方法的简单指针,如下所示:
export class SmbwaService {
getExistingArsByLab(labId: number): Observable<SmwbaAr[]> {
this.otherMethod();
}
otherMethod(): void {
}
}
let method: (x: number) => Observable<SmbwaAr[]>;
method = this.service.getExistingArsByLab;
method(12);
只要它确实调用getExistingArsByLab
方法,它就可以执行。但是,当它尝试调用时,我得到一个错误,otherMethod
因为:
无法读取未定义的属性 otherMethod。
这样做的正确方法是什么?显然,在我的实际代码method
中,根据某些条件将其设置为多种不同方法之一。
解决方案
用于Function.bind
获取绑定到特定值的函数引用this
:
method = this.service.getExistingArsByLab.bind(this.service)
method(2)
推荐阅读
- powershell - Powershell使用文件夹/子文件夹树导入CSV并复制到新目录而不复制
- python - Python Github3 库如何获取 ShortOrganization 生成器的确切内容
- c++ - How can deleting a void pointer do anything other than invoke the global delete operator?
- acumatica - Acumatica 编号序列 - 不能默认为新符号
- c# - 在 C# 插件中调用 Dynamics Web API
- swift - 为什么这个 Switch 语句需要为“Switch Value”和“Compound case”加上括号?
- android - 适配器只显示第一项
- node.js - Mongoose:填充引用的子文档
- python - 根据记录的日期绘制数据
- opentok - Opentok Javascript:自我会话/连接断开?