【问题标题】:How to access this variable inside this function如何在这个函数中访问这个变量
【发布时间】:2017-12-30 22:01:30
【问题描述】:

我在constructor 中有private 变量,在class 中有public 变量。

我使用this关键字来引用这个变量和函数。

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

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

技术: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);

    });
}

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

https://angular.io/guide/http 参考。

【问题讨论】:

  • 你可以使用箭头函数表达式,它保留了 this 的值。使用() => { }函数而不是函数。
  • 您的代码在任何method 之外并且您的class 未正确关闭是否正常?

标签: javascript angular typescript this


【解决方案1】:

利用箭头函数保留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);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 2020-12-28
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多