javascript - “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);
}
}
解决方案
使用.bind
:
function flipBack() {
setInterval(timedFlip.bind(this), 3000);
}
推荐阅读
- reactjs - React Native:错误:jest-haste-map:Haste 模块命名冲突,重复的模块名称:react-animated
- typescript - 如何创建自定义类型保护来检查值是否是给定类的实例?
- swift - UIImageView 变换失去滑动手势
- javascript - 如何更好地组织我的代码以防止出现不良行为?
- c - 遍历文件行并将变量导出到 env
- javascript - ES6图中的最短路径
- python-3.7 - 我希望我的代码只允许输入 1-10
- javascript - 使用 JavaScript 从其他 URL 页面获取 HTML 内容
- r - 在ggplot2中绘制具有离散轴的矩形和线条范围
- java - 如何在 android 中使用 SharedPreferences 从 PhotoView id/image id 中获取价值