The current project I'm working on is creating a game of checkers.
I'm using the function constructor pattern, and I've set a function on a prototype of one of the constructors.
What my issue is, is that the this
keyword points to the global object instead of the caller of the function.
How can I set this
to be the caller of the function?
function Piece(x, y, side) {...}
Piece.prototype.getPossibleMoves = () => {
let possibleMoves = [];
console.log(this); // returns global object
if (this.isKing) {
...
} else {
...
}
return possibleMoves;
}
// Testing
const king = new Piece(5, 5, "bottom");
king.isKing = true;
console.log(king.getPossibleMoves());
So that my desired functionality would be
somePiece.getPossibleMoves()
Rather than
Piece.getPossibleMoves(somePiece);
Which I could implement, but would rather do option one, as it feels more elegant.
The issue was the arrow function expressions don'( refer to this the same way regular function expressions and statements do!