2017-08-16 98 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

相關問題