关于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回答
-
这个是 this 参数,this 参数是个假的参数,它出现在参数列表的最前面,this: void 意味着 addClickListener 期望传入的 onclick 方法不需要 this,这个是给 TypeScript 编译器看的。
而箭头函数的 this 就是它所在上下文的this值, 作为自己的this值。并且在箭头函数中,是没法使用 this 参数的。032019-06-13
相似问题