首页 > 解决方案 > 为什么 Typescript 箭头函数属性可以访问这个

问题描述

我试图了解箭头函数的范围。我在 Angular 中实现了一个小程序,但我有点困惑。在下面的代码中,我真的不明白为什么这会绑定到TestComponent

export class TestComponent {
 a: string = "Hello World";
 myArrowFunction = () => {
  console.log(this.a); //
 }
 constructor(){
  myArrowFunction(); //output: "Hello World"
 }
}

箭头函数没有自己的this,所以this绑定到父函数,对吗?myArrowFunction属于TestComponent,所以thisinmyArrowFunction应该是未定义的,但在上面的示例中this绑定到TestComponent为什么?

    test = {
        b: "Hello World",
        foo: () => {
            console.log(this.b);
        }
    }
        
    test.foo(); //output: undefined

与上面的javascript代码有什么区别?那里 this.b 是未定义的。

标签: javascripttypescriptbindingarrow-functions

解决方案


这是正常的,因为箭头函数 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();


推荐阅读