Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

typescript - this keyword for function parameter

Recently when I use Rxjs 5, I downloaded Rxjs by using npm install [email protected], from downloaded code under node_modules, I found Observable.d.ts in Rxjs folder, I saw it declare its constructor like below:

 *
 * @constructor
 * @param {Function} subscribe the function that is  called when the Observable is
 * initially subscribed to. This function is given a Subscriber, to which new values
 * can be `next`ed, or an `error` method can be called to raise an error, or
 * `complete` can be called to notify of a successful completion.
 */
constructor(subscribe?: <R>(this: Observable<T>, subscriber: Subscriber<R>) => TeardownLogic);

My question is: what is the usage of this keyword in function type declaration of subscribe?: (this: Observable, ...), Does TypeScript has some documentation for this keyword usage like here? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can (since version 2.0 of typescript) specify what is the this you're expecting when a function is invoked.

As described in Specifying the type of this for functions:

Following up on specifying the type of this in a class or an interface, functions and methods can now declare the type of this they expect.

By default the type of this inside a function is any. Starting with TypeScript 2.0, you can provide an explicit this parameter. this parameters are fake parameters that come first in the parameter list of a function

Notice that this won't get translated into js, so it's not a real argument in the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...