function - typescript 接口(interface) : function as property - or - this in interface implementations

标签 function properties interface typescript

我的问题是接口(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/

相关文章:

node.js - 导出nodejs模块中的属性

c++ - c++函数中的通用参数?

python - python中一个装饰器类的解释

javascript - 使用动态计算的名称访问对象属性

java - 扩展抽象类和实现接口(interface)的组合

php - Laravel - 你在哪里存储自己的界面?

python - 如何在python中集成一个简单的菜单

c++ - 隐藏/虚函数使用 C++

c - 如果我想捕获我在 fun1 的正式参数中传递的值,我该怎么做?

python - 如何制作一个函数,一次返回一个列表中的项目?