首页 > 解决方案 > “this”不能引用到嵌套函数,我应该如何解决这个问题?

问题描述

“this”的参考没有达到“timedFlip”功能,我应该如何解决这个问题?我对 Javascript 相当陌生,我主要使用 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);
    }
}

标签: javascriptdom

解决方案


使用.bind

function flipBack() {
    setInterval(timedFlip.bind(this), 3000);
}

推荐阅读