关于this: void

来源:3-19 函数 - this+ 重载

biubiuQAQ

2019-06-13

interface UIElement {
addClickListener(onclick: (this: void, e: Event) => void): void;
}
class Handler {
type: string;
onclickBad = (e: Event) => {
this.type = e.type;
};
}
let h = new Handler();
let uiElement: UIElement = {
addClickListener(onclick: (this: void, e: Event) => void) {}
};
uiElement.addClickListener(h.onclickBad);
老师,这段代码addClickListener(onclick: (this: void, e: Event) => void) {}里面this的类型是void有什么用呢?是代表this的值是不存在的吗?那onclickBad里采用箭头函数,箭头函数的this和this:void不会冲突吗?

写回答

1回答

ustbhuangyi

2019-06-13

这个是 this 参数,this 参数是个假的参数,它出现在参数列表的最前面,this: void 意味着 addClickListener 期望传入的 onclick 方法不需要 this,这个是给 TypeScript 编译器看的。
而箭头函数的 this 就是它所在上下文的this值, 作为自己的this值。并且在箭头函数中,是没法使用 this 参数的。

0
3
biubiuQAQ
回复
ustbhuangyi
哦哦,明白了,谢谢老师
2019-06-13
共3条回复

下一代前端开发语言 TypeScript从零重构axios

课程从零开始重构功能完整的JS库,是学习造轮子的不二之选!

2631 学习 · 877 问题

查看课程