How can I access "this" in Typescript in the same way as I do in Javascript?

Viewed 234

in js, i use following code

function m() {
  console.log(this)
}

m()

this return current context

but in ts, I use following code, this return undefine

function m() {
    // @ts-ignore
    console.log(this)
}

m()

I hope use this get current context in typescript, how to do?

4 Answers

It's because of 'use strict' which used in your typescript by default.

if you try this in js returns the same undefined

'use strict';

function m() {
  console.log(this)
}

m()

The issue is that when you use TS you are running in strict mode and, in strict mode, this of a function is undefined.

Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined:

source

Like the other answers tell you, it's because of the use strict of typescript. To be able to have a this context, you can (but shouldn't) use the new keyword.

playground

function m() {
  // @ts-ignore
  console.log(this);
}

// @ts-ignore
new m();

You can Try Like this,

const that = this;

function m() {
  console.log(that);
}

m();
Related