简体   繁体   中英

Javascript setting a function to a function with a parameter

I'm trying to set an object's "touched" function to another function. I hear about JavaScript and first class functions all the time but still don't have the hang of it. Here's what I have:

customClose.touched = this._close.bind(this);

customClose has a function called "touched" that is empty by default. I want it to be set to another function, this._close.bind, which takes a parameter. How can I make this work?

This will do the trick:

customClose.touched = this._close.bind;

Note that if you use this inside of this._close.bind , when calling customClose.touched(p) , this will refer to customClose .

If you want this to continue referring to this._close , you can use bind :

customClose.touched = this._close.bind.bind(this._close);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM