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
You have to bind
this
to the context of thechangeColour
method to thecubeClass
object:This will ensure that when the
changeColour
method is called within thechange
function, the context is correctly set tocubeClass
, allowing the method to access and modify thewhite
property.Learn what is
this
in JS. That’s a context under a function is called.In your code you lose the context here:
You pass a method as an argument but not its class instance.
There’re 2 fixes: