Referencing functions within object properties does not work

The action1 on your 1st post is clearly a function:

How are we supposed to help you if you mislead us and keep replying w/:


A function which is a property of an object and has to deal w/ the JS keyword this is called an instance method:


If I had access to it from the very beginning I coulda given a better advice to you upfront.

Inside the constructor() of your class Character from your file “character.js” you’ve got this block of code commented out:

this.keys = {
  ArrowUp: this.jump,
}

You can use the Function::bind() method in order to clone any function w/ its this permanently bound to a specific object:

You can apply it like this:

this.keys = {
  ArrowUp: this.jump.bind(this)
}

Or like this as well:

this.keys = {
  ArrowUp: Character.prototype.jump.bind(this)
}

From that on, whatever means you use to invoke that cloned method Character::jump() is gonna work, b/c its this can’t be changed anymore!

2 Likes