javascript - 为什么 Typescript 箭头函数属性可以访问这个
问题描述
我试图了解箭头函数的范围。我在 Angular 中实现了一个小程序,但我有点困惑。在下面的代码中,我真的不明白为什么这会绑定到TestComponent
export class TestComponent {
a: string = "Hello World";
myArrowFunction = () => {
console.log(this.a); //
}
constructor(){
myArrowFunction(); //output: "Hello World"
}
}
箭头函数没有自己的this
,所以this
绑定到父函数,对吗?myArrowFunction
属于TestComponent
,所以this
inmyArrowFunction
应该是未定义的,但在上面的示例中this
绑定到TestComponent
为什么?
test = {
b: "Hello World",
foo: () => {
console.log(this.b);
}
}
test.foo(); //output: undefined
与上面的javascript代码有什么区别?那里 this.b 是未定义的。
解决方案
这是正常的,因为箭头函数 this 指的是上面的对象,所以你的实例。
//console.log(this)
class TestComponent {
myArrowFunction = () => {// function set in instance
console.log(this); //
}
myFunction() {// function set in prototype
console.log(this); //
}
constructor() {
this.a = "Hello World";
this.myArrowFunction(); //output: "Hello World"
}
}
function A() {
this.foo = () => { console.log(this) };// A instance
this.foo()
}
A.prototype.bar = () => { console.log(this) };// global
new A();
//const a = new TestComponent();
推荐阅读
- c# - 从 CRM 获取实体属性 - 指定的转换无效
- python - 如何比较列表列表中的重复元素并在python中相同列表的另一个元素上给出IF条件
- typescript - 如何在 TypeScript 项目中使用 OffscreenCanvas
- json - 都实现 MarshalJSON() 的复合结构的 JSON 编组
- php - 如何将用户表中的ID插入其他表
- gitlab - 如何使 gitlab 页面的“快捷方式”可用?
- android - Picasso 加载横向图像但不将纵向加载到标记的信息窗口中
- python-3.x - 如何测试使用用户界面的功能
- java - 如果文件名包含空格,则使用 HttpURLConnection |HTTP 400 从 url 下载文件
- node.js - 如何从 DynamoDB 获得洗牌结果?