为什么“此”引用AppComponent(范围问题)?

时间:2019-12-19 13:10:11

标签: javascript angular scope this javascript-scope

我正在使用角度8,这是我的代码。

export class AppComponent {

  public auth2: gapi.auth2.GoogleAuth = null;
  public signInStatus: string = "Unknown";

  constructor(private zone: NgZone, private httpClient: HttpClient) {}

  public ngAfterViewInit() {
    this.googleInit();
  }

  public googleInit() {

    // gapi javascript library is loaded in index.html file using
    // <script src="https://apis.google.com/js/client:platform.js"></script>
    // here I just use it
    gapi.load('auth2', () => {

      this.auth2 = gapi.auth2.init({
        client_id: '2xxxxxp.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile'
      });

      this.auth2.then( (googleAuth: gapi.auth2.GoogleAuth) => {

        let isSignedIn: boolean = googleAuth.isSignedIn.get();
        // if I use here debugger; then this referes to AppComponent
        // I come from javascript world, where 'this' refers to current scope
        // why does 'this' refere to AppComponent here?
        this.updateSignInStatus(isSignedIn);

      }, onFailure => {
          console.log("Initialization failed");
      });
    });
  }

  public updateSignInStatus(signedIn: boolean) {

    this.zone.run(() => {
      debugger;
      // I though that 'this' here referes to current scope which
      // is anonymous function. The same question as below
      this.signInStatus = signedIn ? "Yes" : "No";
    });
  } 

我想了解为什么匿名函数中的'this'指向AppComponent。我错过了什么。也许一些文档链接。

enter image description here

0 个答案:

没有答案