使用'this'和内部作用域命名函数的Typescript问题

时间:2013-12-18 19:43:54

标签: javascript typescript

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

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
            ...
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我建议这样的事情:

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);
    }
}