Hi I want to optimize my code so I don't have a lot of if statements. I've been trying to optimize this code witch is inside a Class
if (spot.charAt(1) === "P") this.#getMovesPawn(row, col, validMoves);
if (spot.charAt(1) === "N") this.#getMovesKnight(row, col, validMoves);
if (spot.charAt(1) === "B") this.#getMovesBishoop(row, col, validMoves);
if (spot.charAt(1) === "R") this.#getMovesRook(row, col, validMoves);
if (spot.charAt(1) === "Q") this.#getMovesQueen(row, col, validMoves);
First i tried to try putting all of the functions inside an Object
this.moveFunctions = {"P": this.#getMovesBishoop, "B": this.#getMovesBishoop, "N": this.#getMovesKnight,"Q":this.#getMovesQueen, "R": this.#getMovesRook}
// then executing them
this.moveFunctions["P"](0, 0, []);
but when doing so the this
variable changes from the Class variable where all the info is at to just include the functions
// from this
{
"apple": 1,
"pear": 2
...
}
// to
{"P": this.#getMovesBishoop, "B": this.#getMovesBishoop, "N": this.#getMovesKnight,"Q":this.#getMovesQueen, "R": this.#getMovesRook}
my question is how do i manage to make this.moveFunctions
work or something better? I have searched stackoverflow and google, but nothing i've also tried trying this in python and it worked
CodePudding user response:
You forgot to bind the correct this
- see How does the "this" keyword work?.
When you write a.b()
this is different from const x = a.b; x()
because the syntax of a.b()
automatically passes a
as this
to the method a.b
. This automatic "connection" is lost when you do x()
because it happens only when you do a function call immediately preceded by a property access, but here the property access and the function call happen in two different places.
The behavior you observe is because here there is an automatic "connection" to an object but it's not the object you expected, because ["P"]
is a property access as well (just like .P
) so now you have another a.b()
situation but with a
being this.moveFunctions
!
The solution to both scenarios (no property access before the call at all or property access on an unwanted object) is to either bind
the correct this
to the function (const x = a.b.bind(a); x()
works) or use call
to pass it (const x = a.b; x.call(a)
works too).
In your case, call
is probably the easier way:
this.moveFunctions["P"].call(this, 0, 0, []);