2

the reference for "this" doesn't reach the "timedFlip" function, how should I work around that? I'm fairly new to Javascript, I work mostly backend with Python.

function flipBack() {
    setInterval(timedFlip, 3000);
}

function timedFlip() {
    this.setAttribute('src', 'images/back.png');
}

function flipCard() {
    cardId = this.getAttribute('data-id');
    console.log("User flipped " + cards[cardId].rank);
    console.log(cards[cardId].cardImage);
    console.log(cards[cardId].suit);
    cardsInPlay.push(cards[cardId].rank);
    this.setAttribute('src', cards[cardId].cardImage);
    checkForMatch();
}

function createBoard() {
    shuffle(cards);
    for (var i = 0; i < cards.length; i++) {
        var cardElement = document.createElement('img');
        cardElement.className = "cards";
        cardElement.setAttribute('src', 'images/back.png');
        cardElement.setAttribute('data-id', i);
        cardElement.addEventListener('click', flipCard);
        cardElement.addEventListener('click', flipBack);
        document.getElementById('game-board').appendChild(cardElement);
    }
}
JCaptain
  • 57
  • 4
  • What do you expect `this` to refer to in the `timedFlip` function? – Jamiec Sep 09 '19 at 09:08
  • You can add next parameters in setTimeout and read them in timedFlip. setInterval(timedFlip, 3000, this); and then timedFlip(that) { that.setAttribute( ... – Jan Sep 09 '19 at 09:09

1 Answers1

3

Use .bind:

function flipBack() {
    setInterval(timedFlip.bind(this), 3000);
}
Blue
  • 22,608
  • 7
  • 62
  • 92