【发布时间】: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();
【问题讨论】:
-
你可以使用箭头函数表达式,它保留了 this 的值。使用
() => { }函数而不是函数。 -
您的代码在任何
method之外并且您的class未正确关闭是否正常?
标签: javascript angular typescript this