【问题标题】:How can I access "this" in Typescript in the same way as I do in Javascript?如何以与在 Javascript 中相同的方式在 Typescript 中访问“this”?
【发布时间】:2021-01-05 06:43:02
【问题描述】:

在js中,我使用以下代码

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

m()

返回当前上下文

但是在ts中,我使用下面的代码,这个返回未定义

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

m()

我希望在 typescript 中使用这个获取当前上下文,怎么办?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

就像其他答案告诉你的那样,这是因为打字稿的use strict。为了能够拥有this 上下文,您可以(但不应该)使用new 关键字。

playground

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

// @ts-ignore
new m();

【讨论】:

  • 或者在编译器选项中设置"alwaysStrict"false。
【解决方案2】:

这是因为你的 typescript 中默认使用了“use strict”。

如果你在 js 中尝试这个返回相同的 undefined

'use strict';

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

m()

【讨论】:

    【解决方案3】:

    问题在于,当您使用 TS 时,您在严格模式下运行,而在严格模式下,函数的 this 未定义。

    因此对于严格模式函数,指定的 this 不会被装箱 一个对象,如果未指定,这将是未定义的:

    source

    【讨论】:

    • 任何体面的 JavaScript 开发人员在切换到 TypeScript 之前都在严格模式下运行,除非他们有明确且明确的理由不这样做。
    【解决方案4】:

    你可以试试这样,

    const that = this;
    
    function m() {
      console.log(that);
    }
    
    m();
    

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 2016-07-15
      • 2015-12-18
      • 2021-10-28
      • 1970-01-01
      • 2016-02-26
      • 2018-04-06
      • 2017-03-14
      • 2023-03-16
      相关资源
      最近更新 更多