简体   繁体   中英

How to access additional arguments passed to bind javascript?

I am trying to bind values to a function in a loop. How can I access the binded values in the function?

// ansswer number is is different each time
 btn.find("a").data(this.key, option.slide).bind("click", this._continueOnClick.bind(answerNumber));

Now from the function _continueOnClick , how can I actually access the value of answerNumber ?

The function:

_continueOnClick: function (e) {
    console.log(answerNumber); //fails
}

Bind's first parameter is what you want to pass as this , but it will expect an object here, if you send a primitive it will convert into the Object version, eg. number to Number() , so you could just use this.valueOf() .

But another option, you can pass more params, you can just pass null or some other object as the first parameter. These extra params will then be available in the callback's parameters and can also be primitives, not just objects..

Here is an example..

 for (let answerNum = 0; answerNum < 10; answerNum++) { const btn = document.createElement('button'); btn.innerText = answerNum; document.body.appendChild(btn); btn.addEventListener('click', click.bind(null, answerNum)); } function click(answerNum) { console.log(answerNum); }

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