【发布时间】: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