猿问

如何以与在 Javascript 中相同的方式在 Typescript 中访问“this”?

在 js 中,我使用以下代码


function m() {

  console.log(this)

}


m()

这返回当前上下文


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


function m() {

    // @ts-ignore

    console.log(this)

}


m()

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


绝地无双
浏览 202回答 4
4回答

qq_花开花谢_0

你可以像这样尝试,const that = this;function m() {  console.log(that);}m();

www说

问题是,当您使用 TS 时,您是在严格模式下运行的,而在严格模式下,this一个函数是未定义的。因此,对于严格模式函数,指定的 this 不会装箱到对象中,如果未指定,则 this 将是未定义的:来源

慕尼黑5688855

就像其他答案告诉你的那样,这是因为use strict打字稿。为了能够拥有this上下文,您可以(但不应该)使用new关键字。操场function m() {  // @ts-ignore  console.log(this);}// @ts-ignorenew m();

尚方宝剑之说

这是因为默认情况下在您的打字稿中使用“use strict”。如果你在 js 中尝试这个返回相同的 undefined'use strict';function m() {  console.log(this)}m()
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答