function action1 () {
// Do some action.
}
keys = {
ArrowUp: action1;
}
// Function from P5.js
function keyPressed () {
console.log( `Key ${key} pressed!` );
if ( keys[ key ] !== undefined ) {
// This console.log() shows the referenced function...
console.log( keys[ key ] );
// However the function is not getting called.
keys[ key ](); // It does not work.
}
}
Why such thing is happening in the P5.js? It works perfect in vanilla JS to avoid lots of IFs.
Well, I got the time to dig in into the problem. The âaction1â is in an object, which is lost when I call the function, and the function also calls properties of that object with âthis.â, that would pointing to that object, but ends transforming the âthis.â to the âkeysâ object, which is not the intention.
If you want to see the code, this is the link project: https://editor.p5js.org/kdmb/sketches/vU2TNSuRy
The keys object is in âscripts/game/character.jsâ that have the âaction1â which is the jump(), and the keyPressed function is in âscripts/scenes/game.jsâ
Sorry about the confusion. I started with the code on the post and I kept changing it to all possibilities but nothing worked for me, maybe I was placing it in the wrong places.