JavaScript "this" .replace 回调中的上下文

JavaScript "this" context in .replace callback

考虑以下非常简化的示例:

var some_module = {
    func_a: function() {
        return 'a';
    },
    func_b: function(character) {
        if (character == 'b') {
            console.log(this); //refers to window
            return this.func_a;
        } else {
            return 'X';
        }
    },
    func_c: function() {
        console.log(this); //refers to some_module
        return "abcdefgh".replace(/[abc]/g, this.func_b);
    }
};
some_module.func_c();

这失败了,因为在 func_b 中,"this" 由于调用上下文(据我所知)引用 window。我知道解决方法,通常在嵌套函数时有效,但是在函数用作 .replace() 中的回调的情况下,我如何才能让它工作?

尝试使用 .bind

return "abcdefgh".replace(/[abc]/g, this.func_b.bind(this));

或存储对 this

的引用
func_c: function() {
   var _this = this;

   return "abcdefgh".replace(/[abc]/g, function (char) {
       return _this.func_b(char);
   });
}

Example - 1 Example - 2

您可以使用 ES7 绑定运算符:

return "abcdefgh".replace(/[abc]/g, ::this.func_b);

注意双冒号 ::。如果给出正确的标志,Babel 会支持这一点。参见 https://github.com/zenparsing/es-function-bind. See also http://wiki.ecmascript.org/doku.php?id=strawman:bind_operator

此增强功能的主要目的是阻止无法理解 this 并想知道为什么 setTimeout(this.foo, 1000) 不起作用的人在 SO 上提出相同的问题。