Как привязать контекст в данной ситуации:
{
"use strict";
const field = document.querySelector('.wrapper'),
startGame = document.querySelector('#startGame');
class TicTacToe {
constructor() {
this.started = false;
this.count = 0;
}
start(e) {
e.stopPropagation();
this.started = true;
const createField = document.createElement('table');
createField.classList.add('tic-tac-toe');
for (let i = 0; i < 3; i++) {
const tr = document.createElement('tr');
for (let i = 0; i < 3; i++) {
const td = document.createElement('td');
tr.appendChild(td);
}
createField.appendChild(tr);
}
field.innerHTML = '';
field.appendChild(createField);
createField.addEventListener('click', e => {
game.move(e); // !! Если обращаться к this, то он равен createField
this.move(e);
});
}
move(e) {
e.stopPropagation();
this.count++;
console.log(this.count)
}
}
const game = new TicTacToe();
startGame.addEventListener('click', game.start, {
capture: true
});
}
.wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.tic-tac-toe {
border-collapse: collapse;
}
.tic-tac-toe td {
border: 2px solid rgb(26, 26, 26);
width: 100px;
height: 100px;
text-align: center;
cursor: pointer;
}
<div class="wrapper">
<button id="startGame">Начать!</button>
</div>
Пробовал .call
, не помогло.
Восклицательными знаками показана проблемная строчка.