首页 > 解决方案 > 调用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中,根据某些条件将其设置为多种不同方法之一。

标签: javascripttypescript

解决方案


用于Function.bind获取绑定到特定值的函数引用this

method = this.service.getExistingArsByLab.bind(this.service)
method(2)

推荐阅读