【问题标题】:accessing 'this' in exported function - typescript在导出的函数中访问“this” - 打字稿
【发布时间】:2022-01-03 10:57:53
【问题描述】:

我试图理解在导出函数中尝试访问/传递“this”时遇到的以下错误,我有以下代码:

export async function main() {
try {
    console.log(this)
catch (e: any) {

}

在尝试编译时给我这个错误:

src/main.ts:55:32 - error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

55      console.log( this);
                                  ~~~~

src/main.ts:28:23
    28 export async function main() {
                             ~~~~
    An outer value of 'this' is shadowed by this container.

我不明白为什么我无法访问它 - 'this' 应该是函数范围吗?还是全局对象?谁在隐藏这个变量,我该如何解决?

【问题讨论】:

  • 这取决于你如何称呼它。上面的代码不能确定this 是什么。这就是您收到错误的原因:取决于您如何称呼它 this 可能会有所不同。
  • 我从另一个文件调用(因为它是一个导出函数),只需运行'main()'(async () => { main()})();
  • 在这种情况下,this 将是 undefined(在严格模式下)或全局对象。如果你调用函数时既没有main.call(someThisValue),也没有像const obj = { main }; obj.main()这样的对象属性,那么使用this是没有意义的。

标签: node.js typescript this


【解决方案1】:

错误来自noImplicitThis 编译选项。 您可以删除此选项(不推荐)或声明this 的类型,例如:

export async function main(this: unknown) {
    try {
        console.log(this);
    } catch (e: any) {

    }
}

游乐场链接:https://tsplay.dev/mLLpbm

【讨论】:

  • 但是错误的根源是什么?我的意思是用未知的方式传递它,只需将this 声明为函数的参数。为什么不声明就无法访问this
  • 因为没有定义this应该是什么类型,否则...如果你写main.call(123)this将是new Number(123),如果你写const obj = { main }; obj.main()然后this 将是obj,如果您处于严格模式并且只写main() 那么this 将是undefined,等等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
相关资源
最近更新 更多