javascript - this 变量是 Window 对象或在 Promise 的 then 方法中未定义

标签 javascript ecmascript-6 aurelia

在 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/

相关文章:

javascript - react onClick 不触发 es6

javascript - 使用 Materialise css 在 Aurelia 中选择

javascript - Aurelia 语义下拉列表

javascript - React setstate 方法的回调未触发

javascript - Reactjs 测试 api 调用

javascript - 从所需的对象文字中访问 `this`?

node.js - 无法在 Node.js 中导入 firebase-admin

dependency-injection - 无法注入(inject) aurelia 验证

javascript - 有什么方法可以在 window.onload 中设置 google onload 回调吗?

javascript - MongoDB 获取数据以 HTML 形式显示