Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 836
IcyBrk Avatar asked May 24 '17 16:05

IcyBrk


People also ask

What is a parameter for a function?

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions. For example: function example(parameter) { console.

What is keyword parameter in Python?

Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword. A.

What is the this keyword in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.

What is a function keyword?

The function keyword can be used to define a function inside an expression. You can also define functions using the Function constructor and a function declaration.


1 Answers

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.

like image 120
Nitzan Tomer Avatar answered Sep 30 '22 19:09

Nitzan Tomer