【问题标题】:Keep the context of this after a click event in a function object [duplicate]在函数对象中的单击事件后保留 this 的上下文 [重复]
【发布时间】:2016-09-26 22:36:36
【问题描述】:

我有一个带有函数的对象。这是一个简化的版本:

var app = {

  functOne: function(){
    document.querySelector('button').addEventListener('click', this.functTwo);
  },

  functTwo: function(){
    console.log('Funct Two has Run');
    this.functThree();
  },

  functThree: function(){
        console.log('Funct Three has Run');
  }
};

app.functOne();

functOne 中的应用程序将单击处理程序附加到按钮(以启动 functTwo)。 FunctTwo 应该执行 FunctThree 但“this”的上下文不再是“app”(现在是按钮)。如何从内部(或传递给)functTwo 再次获取“应用程序”(假设应用程序不只是像上面的示例那样附加到窗口)。

【问题讨论】:

    标签: javascript scope javascript-objects onclicklistener dom-events


    【解决方案1】:

    这是通过使用Function.prototype.bind()实现的:

      functOne: function(){
        document.querySelector('button').addEventListener('click', this.functTwo.bind(this));
      },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多