如何在此函数中访问此变量 [英] How to access this variable inside this function

查看:111
本文介绍了如何在此函数中访问此变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构造函数 public 中有私有变量类中的变量

我使用 this来引用这些变量和函数 keyword。

I refer to this variables and functions using this keyword.

如果我尝试在此函数中访问此变量,我将获得 undefined

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

我是 typescript 的新手,如何在此函数中访问此变量?

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

技术:Typescript,Angular 2,Angular 1.6.5,JavaScript

Technology: Typescript, Angular 2, Angular 1.6.5, JavaScript

admin-company-settings.ts

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);

    });
}

我怀疑它可以被 .bind使用(这个)但我不熟悉在哪里添加 .bind();

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 参考。

推荐答案

利用箭头功能保留的价值

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

这篇关于如何在此函数中访问此变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆