skip to Main Content

I want to pass a class method into a function and call that method inside that function. Here is the code:

class Cube {
    constructor() { //setup the cube and if using a previous cube, setup with that
        this.white = 'white'
    }
    changeColour(){
        this.white = 'yellow'
    }
}

const cubeClass = new Cube()

function change(classMethod){
    classMethod()
}
change(cubeClass.changeColour)

I am getting this error:

Cannot read properties of undefined (reading 'white')

I want it to be able to change the colour in the class, from calling the change function, so it can change it from white to yellow

2

Answers


  1. You have to bind this to the context of the changeColour method to the cubeClass object:

    change(cubeClass.changeColour.bind(cubeClass));
    

    This will ensure that when the changeColour method is called within the change function, the context is correctly set to cubeClass, allowing the method to access and modify the white property.

    Login or Signup to reply.
  2. Learn what is this in JS. That’s a context under a function is called.
    In your code you lose the context here:

    change(cubeClass.changeColour);
    

    You pass a method as an argument but not its class instance.
    There’re 2 fixes:

    1. bind the class instance to your argument:
    change(cubeClass.changeColour.bind(cubeClass); 
    
    1. a more cleaner way is to provide a wrapper function where the context is defined:
    change(() => cubeClass.changeColor());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search