将Typescript函数作为Javascript函数传递

时间:2013-07-25 09:08:16

标签: javascript typescript breeze

我使用微博的打字稿。如何将打字稿功能传递给executeQuery.then

class MyClass{
 ...
    myFunc(data:any):void{
       ...
    }

    doQuery():void{
        var manager = new breeze.EntityManager('/breeze/dbentities');
        var query = breeze.EntityQuery.from("Corporations").where("Name", "startsWith", "Zen");
        manager.executeQuery(query)
               .then(this.myFunc);  // does not work!
    }
}

2 个答案:

答案 0 :(得分:1)

使用this.myFunc代替myFunc

这可能是一个背景问题。请尝试使用this.myFunc.bind(this)代替this.myFunc


有关上下文的详细信息,请参阅MDN的"this""Function.prototype.bind"文章。

答案 1 :(得分:0)

首先,这在我自己的课程中完美运作。什么是“不工作”,抛出了什么错误信息?

其次,为了确保“this”是我的typescript类上下文,我总是使用这样的lambda:

doQuery(): void {
    ...
    manager.executeQuery(query).then((data: breeze.QueryResult) => {
        this.myFunc(data);
    });
}

在这种情况下,TS编译器在doQuery函数的开头生成一个“var _this = this”,它是您的类上下文,并将“this.myFunc(data)”调用转换为“_this.myFunc(data)”

最好使用类型声明,例如“breeze.QueryResult”而不是任何。