提问人:ddor254 提问时间:1/3/2022 更新时间:1/3/2022 访问量:296
在导出的函数中访问“this” - TypeScript
accessing 'this' in exported function - typescript
问:
我正在尝试理解尝试在导出函数中访问/传递“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”应该是功能范围吗?还是全局对象?谁在隐藏这个变量,我该如何解决这个问题?
答:
1赞
HTN
1/3/2022
#1
错误来自编译选项。
您可以删除此选项(不推荐)或声明以下类型的类型:noImplicitThis
this
export async function main(this: unknown) {
try {
console.log(this);
} catch (e: any) {
}
}
游乐场链接: https://tsplay.dev/mLLpbm
评论
0赞
ddor254
1/3/2022
但是错误的根源是什么?我的意思是用 unknown 传递它,只需声明作为函数的参数。为什么我不能在不声明的情况下访问它?this
this
1赞
CherryDT
1/3/2022
因为没有定义否则应该是什么类型......如果你写,将是 ,如果你写,那么将是 ,如果你处于严格模式,只是写,那么将是 ,等等。this
main.call(123)
this
new Number(123)
const obj = { main }; obj.main()
this
obj
main()
this
undefined
评论
this
this
(async () => { main()})();
this
undefined
main.call(someThisValue)
const obj = { main }; obj.main()
this