在对象文字中的函数内使用“this”时的预期行为是什么?
例如,假设我有一个类型foo,它只有一个名为“bar”的函数,而不是其他属性.但是在fooObj.bar方法中,我能够访问this.baz(其中“baz”不是“foo”类型的属性)我没有看到错误.不应该打字稿错误,因为fooObj上没有“baz”吗?
type foo = {
bar(): void;
}
var fooObj: foo = {
bar: () => {
// TS does not error out when I access this.baz
console.log(this.baz);
}
}
解决方法:
你正在使用箭头功能,which has lexical this
.
但是,对象文字中非箭头函数属性的简写更短:
var fooObj: foo = {
bar() {
console.log(this.baz);
}
}