【问题标题】:JavaScript "this" context in .replace callback.replace 回调中的 JavaScript“this”上下文
【发布时间】:2015-01-29 12:37:10
【问题描述】:

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

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”指的是窗口,因为调用上下文(据我所知)。我知道解决方法,通常在嵌套函数时起作用,但是在这种情况下,函数用作 .replace() 中的回调,我怎样才能让它工作?

【问题讨论】:

  • 您应该深呼吸并退后一步,确保您真正了解this 的含义以及它的来源。有很多很好的教程,包括关于 SO 的答案,例如stackoverflow.com/questions/3127429/…。这个问题已经以一种或另一种形式被问过几十次了。

标签: javascript callback this


【解决方案1】:

尝试使用.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

【讨论】:

    【解决方案2】:

    你可以使用 ES7 绑定操作符:

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

    注意双冒号::。如果给定正确的标志,这将受到 Babel 的支持。见https://github.com/zenparsing/es-function-bind。另见http://wiki.ecmascript.org/doku.php?id=strawman:bind_operator

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 2011-01-08
      相关资源
      最近更新 更多