“ this”在类的函数中未定义

时间:2019-01-12 11:39:30

标签: javascript node.js

execute() {
    //`this` is defined
    return MongoClient.connection.then(function(db) {
        //`this` is undefined from here on
        db.db('main').collection('bans').insertOne({
            "id": this.id,
            "reason": this.reason,
            "offence": this.offence,
            "proof": this.proof,
            "reporter": this.reporter,
            "date": this.date,
            "for_voters": this.for_voters,
            "against_voters": this.against_voters,
            "appeal": (this.appeal.appeal_text) ? this.appeal : undefined,
        });
        return true;
    });

我得到一个错误,this未定义。上面的代码块在具有构造函数的类中,该构造函数具有this.id,this.date等。 我将如何解决这个问题?我尝试将this作为参数包含在MongoClient.connection.then(function(db, **this**))

0 个答案:

没有答案