![](/img/trans.png)
[英]how to pass variable from one function to another function in javascript
[英]How to pass this from one function to another function in vanilla JavaScript?
我有當前的代碼塊:
cells.forEach(cell => {
cell.addEventListener('click', clickHandler);
})
let turn = 0;
function clickHandler() {
alternateTurn(this).bind(this);
// do more things here
}
function alternateTurn() {
if(turn % 2 === 0) {
this.innerHTML = 'X';
this.style.color = 'red';
} else {
this.innerHTML = 'Y';
this.style.color = 'blue';
}
turn++;
this.classList.add('decoration');
}
現在我想將this
上下文從 clickHandler function 傳遞到alternateTurn function。
call
或apply
。 但是當我想立即調用第二個 function 時,使用call
和apply
。 但是,在這種情況下,我需要立即調用它嗎?this
,我如何在第二個 function 中調用它? 那么call
和apply
立即調用它並bind
返回 function 與this
綁定,在您的情況下,您似乎只需要立即使用call
或apply
調用它:
cells.forEach(cell => { cell.addEventListener('click', clickHandler); }) function clickHandler() { alternateTurn.call(this); } function alternateTurn(e) { console.log(e.target, 'that') if(turn % 2 === 0) { this.innerHTML = 'X'; this.style.color = 'red'; } else { this.innerHTML = 'Y'; this.style.color = 'blue'; } turn++; this.classList.add('decoration'); }
但是,如果可能,直接調用alternateTurn
可能更容易。 您在這里擁有的是一種稱為pass-through method
的模式,其中該方法除了調用另一個執行完全相同的事情的方法之外沒有其他用途。
這不是真的推薦,但您的代碼可能會做更多的事情:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.