在 ES2015(以前的 ES6)中,我认为使用箭头语法应该导致 this
变量成为您所在的对象,从而使旧的 var that = this
技术过时。
但是,在 Promise 的 then
部分的函数中,this
变量是 Window
对象(在 Chrome 中)或未定义
(在 FF 和 IE11 中):
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject(HttpClient)
export class InvoiceGenerator {
items = [];
constructor(http) {
this.http = http;
}
activate() {
this.http
.get(`http://${window.location.host}/api/invoice`)
.then(response => {
this.something = response.someProperty; // this is the Window
}).catch(err => {
console.log(err);
});
}
}
顺便说一句,我正在使用 Aurelia,以防它很重要。
如何让 this
变量成为我当前所在的对象(我的 Aurelia View 模型),而不使用旧的 var that = this
技术?
最佳答案
在回调中使用“this”引用之前,您需要在类中声明“something”属性,因为回调中的“this”不包含“something”属性,也不会创建它。
export class InvoiceGenerator {
something = [];
constructor(http) {
this.http = http;
}
activate() {
this.http
.get(`http://${window.location.host}/api/invoice`)
.then(response => {
this.something = response.someProperty; // this is the Window
}).catch(err => {
console.log(err);
});
}
}
我没有尝试过,但我相信 Typescript 会捕获该错误。
关于javascript - this 变量是 Window 对象或在 Promise 的 then 方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30786815/