6

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?

Liam
  • 27,717
  • 28
  • 128
  • 190
chikadance
  • 3,591
  • 4
  • 41
  • 73
  • might wanna also read https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript – Anunay Sep 18 '20 at 10:26
  • 1
    Related (and also a possible solution): [Prevent "use strict" in typescript?](https://stackoverflow.com/questions/38269478/prevent-use-strict-in-typescript) – Liam Sep 18 '20 at 10:56

4 Answers4

0

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()
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
0

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

Liam
  • 27,717
  • 28
  • 128
  • 190
sam256
  • 1,291
  • 5
  • 29
  • 1
    And any decent JavaScript developer was running in strict mode before they switched to TypeScript unless they had a specific and well defined reason for not doing so. – Aluan Haddad Sep 18 '20 at 12:03
0

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();
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
0

You can Try Like this,

const that = this;

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

m();
Prakash Harvani
  • 1,007
  • 7
  • 18