I want to bind a function with specific arguments to an .onclick()
in a context like this:
for(var i = 0; i < 3; i++) {
for(var j = 0; j < 3; j++) {
var button = document.createElement("button");
button.textContent = board[i][j];
button.onclick = function() {
makeMove(i,j); //The function will always be called with the last value of i and j.
}
document.body.appendChild(button);
}
}
I can solve this by using makeMove.bind(null,i,j)
or function(arg1,arg2){ return function() { makeMove(i,j); }}(i,j)
but both does not seem right because Function.prototype.bind()
was created to bind a context to this
and I don't want to use IIFE because it is a TicTacToe example for beginner programmers.
Is there another way to solve this problem without much complexity?