我的问题是接口(interface)中的函数和实现中的 this
关键字。
假设以下场景:
我有一个实现特定接口(interface)的类。接口(interface)可以定义如下:
module Contracts
{
export interface ISomeInterface
{
Foo: () => void;
}
}
实现可能如下所示:
module MyClasses
{
export class SomeClass implements Contracts.ISomeInterface
{
public SomeValue: string = "Some fancy value";
public Foo()
{
alert(this.SomeValue);
}
}
}
当我从实例中调用它时这有效,如下所示:
var someClass = new MyClasses.SomeClass();
someClass.Foo();
现在,由于某些情况,函数没有像这样被调用,而是在另一个上下文中被调用,导致 this
完全不同,导致 this.SomeValue
未定义。
我了解到,如果您想在另一个上下文中调用一个函数时正确访问 this
,您可以像这样使用粗箭头:
public Foo = () =>
{
alert(this.SomeValue);
}
(更多信息:https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript#use-instance-functions)
但这并不满足接口(interface)。 Foo 在类中被识别为属性,但接口(interface)将其定义为方法。有道理。
那么我该如何解决这个问题呢?
最佳答案
您要做的最简单的事情就是将绑定(bind)函数传递给您的回调(或其他)。
例如:
let a: SomeClass = new SomeClass();
let boundFoo = a.Foo.bind(a);
boundFoo(); // this should be as you intended
More about the bind
function in MDN
编辑
我检查了your code in Playground看起来还不错。
该类实现接口(interface),编译器不报错。
关于function - typescript 接口(interface) : function as property - or - this in interface implementations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36860857/