【问题标题】:Pass Typescript function as a Javascript function将 Typescript 函数作为 Javascript 函数传递
【发布时间】:2014-05-23 16:00:56
【问题描述】:

我在微风中使用打字稿。如何将打字稿函数传递给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!
    }
}

【问题讨论】:

    标签: javascript typescript breeze


    【解决方案1】:

    使用this.myFunc 而不是myFunc

    这可能是上下文问题。试试this.myFunc.bind(this) 而不是this.myFunc


    有关 context 的更多信息,请参阅来自 MDN 的 "this""Function.prototype.bind" 文章。

    【讨论】:

    • 抱歉忘记添加这个。但是对于this,该函数也不会被调用。
    • 那可能是上下文问题,试试this.myFunc.bind(this)
    • 我应该在哪里调用绑定?
    • 它将函数的执行上下文(又名this)绑定到this。我更新了我的答案,请参阅链接文章。这些绝对比我糟糕的解释要好。另请注意,它与 TypeScript 无关。 :)
    【解决方案2】:

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

    其次,为了确保“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”之类的类型声明而不是任何类型声明。

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 2012-09-12
      • 2018-02-23
      相关资源
      最近更新 更多