在不丢失 'event' 对象的情况下,使用 'bind(this) 发送额外参数

Send extra parameters with 'bind(this) while not losing 'event' object

我在代码中使用了一个对象文字模式,我正在尝试使用 'bind' 将对象名称作为对另一个函数的引用传递。我还需要传递第二个参数,但是当我这样做时,我无法访问 'event' 对象。

var obj = {
  init: function() {
    this.trig();
  },

  trig: function() {
    $('.addButton').on('click', this.doSomething.bind(this, secondParameter))
  },

  doSomething: function(e,args) {
    e.preventDefault(); // erroring here e.preventDefault is not a function 

    //rest of the code 
  }
}

obj.init();

知道如何发送第二个参数同时仍然可以访问事件对象吗?

不需要使用 bind,因为 doSomething 已经是对象的方法,所以您只需将事件作为参数传递

var obj = {
  init: function() {
    this.trig();
  }

  trig: function() {
    $('.addButton').on('click', (event) => this.doSomething(event))
  },

  doSomething: function(e) {
    e.preventDefault(); // erroring here e.preventDefault is not a function 

    //rest of the code 
  }
}

obj.init();

doSomething 只接受一个参数。如果你想让它接受两个,那么你需要这样写。

参见the MDN documentation for bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

所以你需要把接受绑定参数的变量放在接受事件对象参数的变量之前:

doSomething: function (boundArgument, e) {