我正在尝试将对象的“触摸”功能设置为另一个功能。我一直听说 JavaScript 和一流的函数,但仍然没有掌握它的窍门。这是我所拥有的:
customClose.touched = this._close.bind(this);
customClose 有一个名为“touched”的函数,默认为空。我希望将它设置为另一个函数 this._close.bind,它接受一个参数。我怎样才能使这项工作?
我正在尝试将对象的“触摸”功能设置为另一个功能。我一直听说 JavaScript 和一流的函数,但仍然没有掌握它的窍门。这是我所拥有的:
customClose.touched = this._close.bind(this);
customClose 有一个名为“touched”的函数,默认为空。我希望将它设置为另一个函数 this._close.bind,它接受一个参数。我怎样才能使这项工作?
It turns out my original implementation was correct. The problem was that the close button had moved due to another change I had made. Since it's invisible, I didn't notice. Binding the function to the object's function is done as follows:
customClose.touched = this._close.bind;
这可以解决问题:
customClose.touched = this._close.bind;
注意,如果你使用this
inside of this._close.bind
,在调用的时候customClose.touched(p)
,this
会引用customClose
.
如果要this
继续引用this._close
,可以使用bind
:
customClose.touched = this._close.bind.bind(this._close);