“this”和内部作用域命名函数的打字稿问题

Typescript issue with 'this' and inner scoped named function

本文关键字:函数 问题 this 内部 作用域      更新时间:2023-09-26

写这个的正确方法是什么?

class Test {
    log(data) { ... }
    queryFailed(error) { ... } // Generic error handler
    runQuery(data) {
        doStuff()
        .then(querySuccess)
        .catch(this.queryFailed);
        function querySuccess(data) { // query specific success handler
            this.log("Success!"); // "this" is undefined
            ...
        }
    }
}

我知道我可以像以下那样内联完成:

class Test {
    log(data) { ... }
    queryFailed(error) { ... } // Generic error handler
    runQuery(data) {
        doStuff()
        .then((data) => {
            this.log("Success!"); // 'this' is really '_this' now and set to 'this' right above 'doStuff()' in the compiled javascript
            ...
        })
        .catch(this.queryFailed);
        function querySuccess
    }
}

但这掩盖了doStuff()结果的逻辑

内联使用 .bind(this) 是正确的方式吗?

class Test {
    log(data) { ... }
    queryFailed(error) { ... } // Generic error handler
    runQuery(data) {
        doStuff()
        .then(querySuccess.bind(this))
        .catch(this.queryFailed);
        function querySuccess(data) { // query specific success handler
            this.log("Success!"); // "this" works
            ...
        }
    }
}

我会建议这样的事情:

class Test {
    log(data) { }
    static queryFailed(error) { } // Make sure we don't try to use 'this' here
    runQuery(data) {
        var querySuccess = data => { // query specific success handler
            this.log("Success!"); // Correct 'this'
        }
        doStuff()
        .then(querySuccess)
        .catch(Test.queryFailed(error));
    }
}

或者:

class Test {
    log(data) { }
    static queryFailed(error) { }
    querySuccess = (data) => {
        this.log('Success');
    }
    runQuery(data) {
        doStuff()
        .then(this.querySuccess)
        .catch(Test.queryFailed);
    }
}