【问题标题】:TypeScript: tell what is the current context to an external functionTypeScript:告诉外部函数的当前上下文是什么
【发布时间】:2016-03-03 09:25:34
【问题描述】:

有什么方法可以告诉 TypeScript 编译器外部函数的当前上下文是什么?最好在函数本身的签名上。

目前我正在使用类型转换来解决这个问题。

这里是一个示例代码:

module ui
{
    class Hyperlink
    {
        element: HTMLAnchorElement;
        constructor(url:string,text:string){
            this.element = document.createElement("a");
            this.element.setAttribute("href",url);
            this.element.innerText = text;
            this.element.addEventListener(
                "click", 
                genericOutOfClassFunction.bind(this), <----- binds the current context
                false
            );
            // ...
        }
    }

    // [...]

    function genericOutOfClassFunction(e: Event) {
        var el = this.element; // <---------- compiler error
        // ...

        // alternatively, I've being using:
        var self = <Hyperlink>this;
        var el = self.element; // <--------- no error, but ugly =(
        // ...
    }

    // [...]

}

【问题讨论】:

    标签: javascript casting typescript1.6


    【解决方案1】:

    是的,你可以使用this参数 [link to docs]

    你只需要声明上下文,就像声明函数参数this一样。在您的情况下,它将是:

    function genericOutOfClassFunction(this: HTMLElement, e: Event) {
      // "this" is type of HTMLElement
    }
    

    它可能看起来像添加了新的函数参数,但它没有。它只是将this 设置为指定的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-12
      • 2020-07-27
      • 1970-01-01
      • 2011-06-13
      • 2013-04-21
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多