2017-08-16 97 views
0

我看到下面的一段TypeScript,“this”用作函数的参数。什么意思?为什么像这样使用它? ----“brushended(this:SVGGElement){”。在作为函数参数使用的Typescript中,“this”的含义

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(); 
} 
+3

这意味着[文件说,它确实]什么(https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters)。 – 2017-08-16 05:02:52

回答

0

TLDR;

这是TypeScript在函数内使用this.xxx时执行静态分析的一种方法,并且可以防止在this指针上执行期望特定类型的函数。它在JavaScript中没有表示。

加长版:

正如你可能知道,在JavaScript this可以根据函数是如何被调用很多不同的东西。例如:你可以使用func.apply选择哪个参考被放在this指针

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

拿这个打字稿代码,例如:

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

在这里,我指定功能foo要经常在this指针上执行string。这意味着,只调用编译错误结果:

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

相关问题