How to access this variable inside this function

2020-05-06 11:22发布

问题:

I have private variables in constructor and public variables in the class.

I refer to this variables and functions using this keyword.

I am getting undefined if I try to access this variables inside this function.

I am new to typescript, how can I access this variable inside this function?

Technology: Typescript, Angular 2, Angular 1.6.5, JavaScript

admin-company-settings.ts

import { Component } from '../../../../common/extentions/to-angular2';
import { Http } from '@angular/http';

export class AdminCompanySettings {
    public company: any;
    constructor(private $http: ng.IHttpService) {
        //
    }

    this.company = "New company";
    console.log("Prints all public variables", this); //prints all variables

    var data = { url: www.google.com, data: { user: value } }

    this.$http(data).then(function (response) {

        console.log(response);
        console.log(this.company); // undefined cannot access company
        console.log("Prints window object", this); //this will print window 
                                                   //and not company var or 
                                                   //other scope vars
    }).catch(function (error) {

        console.log(error);

    });
}

I suspected it can be used by .bind(this) but I am not that familiar with where to add .bind();

https://angular.io/guide/http for ref.

回答1:

Make use of Arrow function which preserves the value of this

this.$http(data).then((response) => {
        console.log(response);
        console.log(this.company);
        console.log("Prints window object", this);
    }).catch(function (error) {
        console.log(error);
    });