javascript - 将此参数绑定(bind)到命名参数

标签 javascript jquery prototype

在这种情况下,我的代码结构如下:

 Thing.prototype = {

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

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

 }

如何绑定(bind)这个东西 this self 的上下文参数并仍然保留 this 的行为对象就像没有使用 bind 绑定(bind)参数一样方法?

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

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

最佳答案

How could one bind the Thing this context to the self argument and still keep the behavior of the this object as if no arguments were bound using the bind method?

您不会为此使用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
}

关于javascript - 将此参数绑定(bind)到命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29943717/

相关文章:

JavaScript:当数组为空时解构对象数组时出错

javascript - 使用 ID 正则表达式或冗余类的 Jquery 选择器

javascript - 对象原型(prototype)方法中私有(private)变量的作用域

javascript - 动态为 JavaScript 对象分配属性和值

javascript - jQuery 根据高度拆分内容

javascript - JavaScript 中的原型(prototype)链

javascript - WEBPACK - 我如何需要原型(prototype)函数?

javascript - 添加和删​​除具有关联数字输入值的文本字段

javascript - 哪种转换类型获取所有 Chrome 浏览历史记录?

jquery - 动态创建的字段