TypeScript:如何从另一个函数调用成员函数?

Dav*_*len 0 this typescript

我试图从另一个成员函数调用成员函数 - 并失败.我认为这很容易找到,但经过10分钟的搜索,我找不到这里的错误.

在下面的代码中(是的,我知道pausecomp是一个很大的禁忌,我只是试图测试可能的竞争条件):

class LayoutWorker {
    /*
     Specific events handlers.
     e is the object sent by the client. See events.layout for object definitions.
     */
    handlers = {
        textadd: function (e) {
            for (var ind=0; ind<10; ind++)
            {
                console.log("entering textadd = " + e);
                // Do the work and call the client back if needed. You can pass to the client any object.
                e.text += " -- Hello back from the worker!";
                postClientMessage(e);

                this.pausecomp(4000);
            }
        },

        urgent: function (e) {
            for (var ind=0; ind<10; ind++)
            {
                console.log("entering urgent = " + e);
                // Do the work and call the client back if needed. You can pass to the client any object.
                e.text += " -- Hello back from the worker!";
                postClientMessage(e);

                this.pausecomp(1000);
            }
        }

    };

    handleEvent(e) {
        console.log("entering handleEvent = " + e);
        // Call the specific handler.
        this.handlers[e.id](e);
    }

    pausecomp(millis : number) : void
    {
        var date = new Date();
        var curDate = new Date();
        while(curDate - date < millis)
            curDate = new Date();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的时候,我得到:Uncaught TypeError:Object#没有方法'pausecomp'

我有什么不对?

谢谢 - 戴夫

nik*_*eee 7

在你的例子中,this指的是函数handler.您还可以使用lambda表达式(() =>)或实例函数(foo() {}).

如果您使用的是lambda,this请参阅MyClass.以下是定义类实例函数的一些选项:http://bit.ly/1ep5dMk

因为它handlers是一个独立的类,它有自己的成员,所以它不能引用LayoutWorker - 除非你使用lambda.

你有3个选择:

  • 传递LayoutWorker某个地方的实例
  • pausecomp方法声明为publicstatic并用于LayoutWorker.pausecomp(arg)调用.
  • 使用lambda(参见TypeScript playground的例子)

我创建了3个提到的选项的概述:http: //bit.ly/1kOeWtS

一些建议:

定义处理程序接口和/或单独的类,以更清晰地查看类模型.这有助于理解this无法引用LayoutWorker.