簡體   English   中英

如何在原版 JavaScript 中將其從一個 function 傳遞到另一個 function?

[英]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。

  1. 我怎么做? 我在這里看到答案說我應該使用callapply 但是當我想立即調用第二個 function 時,使用callapply 但是,在這種情況下,我需要立即調用它嗎?
  2. 一旦我從 clickHandler function 傳入this ,我如何在第二個 function 中調用它?

那么callapply立即調用它並bind返回 function 與this綁定,在您的情況下,您似乎只需要立即使用callapply調用它:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM