"这个"的含义在用作函数参数的Typescript中

时间:2017-08-16 04:51:43

标签: typescript

我在下面看到了一段TypeScript,"这个"用作函数的参数。这是什么意思?为什么这样使用? ----" brushended(这:SVGGElement){"。

function brushended(this: SVGGElement) {
  let e = <D3BrushEvent<any>>d3.event;
  let s: BrushSelection = e.selection;
  if (!s) {
    if (!idleTimeout) {
      self.ngZone.runOutsideAngular(() => {
        idleTimeout = window.setTimeout(idled, idleDelay);
      });
      return idleTimeout;
    }
    x.domain(x0);
    y.domain(y0);
  } else {
    x.domain([s[0][0], s[1][0]].map(x.invert, x));
    y.domain([s[1][1], s[0][1]].map(y.invert, y));
    d3Svg.select<SVGGElement>('.brush').call(brush.move, null);
  }
  zoom();
}

1 个答案:

答案 0 :(得分:1)

<强> TLDR;

这是TypeScript在函数内部使用this.xxx时执行静态分析并防止执行需要this指针上特定类型的函数的方法。它在JavaScript中没有表示。

更长的版本:

您可能知道,在JavaScript中this可能有很多不同的东西,具体取决于函数的调用方式。例如:您可以使用func.apply选择将哪个引用放在this指针

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

以此TypeScript代码为例:

function foo(this: string, n: number){
    console.log(this, n);
}

这里我指定函数foo应始终在string指针上使用this执行。这意味着只调用结果导致编译器错误:

foo(42); // Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'string'.

在与使用JavaScript中this指针的“功能”的框架进行交互时尤其有用。例如:rxjs http://reactivex.io/rxjs/中的Observable上的运算符。

更多信息:https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters