【问题标题】:Bind this argument to named argument [duplicate]将此参数绑定到命名参数[重复]
【发布时间】:2015-04-29 12:26:25
【问题描述】:

如果我的代码结构如下:

 Thing.prototype = {

    doSomething: function() {
      $(selector).click(this.handleClick.bind(null, this));
    },

    handleClick: function(self, event) {
      console.log(this); //Window
      console.log(self); //Thing
    }

 }

如何将 Thing this 上下文绑定到 self 参数并仍然保持 this 对象的行为,就好像使用 bind 方法没有绑定任何参数一样?

注意:我知道我可以绑定 this 并使用 e.originalEvent.target 来获得我想要的行为,但我只是好奇是否还有其他方法

我希望我能完成我想要实现的目标,如果有任何不明确的地方,请发表评论。

【问题讨论】:

  • 不,我想使用处理程序的原始 this(被点击的元素),但将 Thing this 传递给 self 变量。

标签: javascript jquery prototype


【解决方案1】:

如何将 Thing this 上下文绑定到 self 参数,并且仍然保持 this 对象的行为,就好像没有使用 bind 方法绑定任何参数一样?

您不会为此使用bind,因为您希望this 是动态的。而是:

doSomething: function() {
  var self = this;
  $(selector).click(function(e) {
      return self.handleClick.call(this, self, e);
  });
},

handleClick 期间,this 将引用被点击的元素,第一个参数是Thing 实例,第二个参数是事件:

handleClick: function(self, event) {
  console.log(this);  // The clicked element
  console.log(self);  // The Thing
  console.log(event); // The event
}

【讨论】:

  • 太好了,我仍在努力解决bind 的行为。如果有什么可用的,欢迎从文档页面对此行为进行全面解释:)
  • @SpyrosMandekis here 是关于 .bind() 的一些不错的文档,其中包含示例,但 T.J. Crowder 下面指向规范的链接应该更加精确,尽管很干。
  • @SpyrosMandekis:有the specification。 :-) 从根本上说,如果您希望在 调用 函数时确定 thisbind 不是正确的工具,因为它会提前修复 this 的内容。
猜你喜欢
  • 2021-05-12
  • 2021-08-13
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 2011-01-10
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多