【问题标题】:JavaScript - this inside of timeout with arrow functions [duplicate]JavaScript - 带有箭头函数的超时内部[重复]
【发布时间】:2017-03-10 12:38:53
【问题描述】:

为什么setTimeout中的this不等于使用箭头函数时调用渲染函数的对象?

 class X {
      constructor(config) {
        this.data = config.data;
        this.render_ = config.render;
      }
      render() {
        this.render_(this.data);
      }
    }
    var x = new X({
      data: [1, 2, 3],
      render: (data) => {
        setTimeout(() => {
          console.log(this);
        }, 200);
      }
    });
    x.render();

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    阅读arrow function documentation 中“箭头函数用作方法”的部分

    总结:箭头函数只是简单地不绑定this 或它们自己的this 版本,而是引用全局Window 对象。

    【讨论】:

    • 这个问题似乎是关于this,而不是arguments
    • 更新了@FelixKling 我在看上面的部分:')
    【解决方案2】:

    因为arrow functions词法绑定的。这意味着它们在声明时具有“this”的价值。它们不受修改this 值的其他方式的影响,包括作为bindapplycall 等方法或函数调用。

    function F() {
      this.type = 'F';
      this.logTypeExpression = function() {
        console.log(this.type);
      };
      this.logTypeArrow = () => {
        console.log(this.type);
      };
    }
    
    function G() {
      this.type = 'G';
    }
    
    var f = new F();
    var g = new G();
    
    f.logTypeExpression(); // F
    f.logTypeArrow(); // F
    
    // Now lets give these functions to G
    g.logTypeExpression = f.logTypeExpression;
    g.logTypeArrow = f.logTypeArrow;
    
    g.logTypeExpression(); // G
    g.logTypeArrow(); // F(!) (That's because `this` was assigned by the arrow function)

    【讨论】:

      【解决方案3】:

      在创建箭头函数时,this 没有绑定到任何对象,所以它仍然引用window。如果您想引用该特定实例,也许您想尝试console.log(x);

      【讨论】:

      • 这应该是一个评论,充其量。问题是this 没有引用x 对象。
      【解决方案4】:

      下面的代码仅包含对您使用对象文字语法创建的函数的引用。

      this.render_ = config.render;
      

      使用 bind(this) 将告诉函数在 X 对象的实例中调用函数时使用参数对象作为 this 引用。

      class X {
          constructor(config) {
              this.data = config.data;
              this.render_ = config.render.bind(this);
          }
          render() {
              this.render_(this.data);
          }
      }
      

      此外,在您的代码 sn-p 中,它是箭头函数还是正则函数表达式都没有关系。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-29
        • 2023-03-08
        • 2018-06-30
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        • 2020-11-08
        相关资源
        最近更新 更多