英文:
Pass Class method in a functions aruguments to call within the function
问题
以下是翻译好的代码部分:
class Cube {
constructor() { // 设置立方体,并且如果使用先前的立方体,则用它来设置
this.white = 'white';
}
changeColour(){
this.white = 'yellow';
}
}
const cubeClass = new Cube();
function change(classMethod){
classMethod();
}
change(cubeClass.changeColour);
出现的错误是:
无法读取未定义的属性(读取 'white')
我希望它能够通过调用 change 函数来改变类中的颜色,使其从白色变为黄色。
英文:
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
答案1
得分: 1
你必须将this绑定到changeColour方法的上下文,以便绑定到cubeClass对象:
change(cubeClass.changeColour.bind(cubeClass));
这将确保在change函数内调用changeColour方法时,上下文正确设置为cubeClass,允许该方法访问并修改white属性。
英文:
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.
答案2
得分: 0
学习什么是JavaScript中的this。这是函数下的上下文称之为。
在你的代码中,你失去了上下文:
change(cubeClass.changeColour);
你传递了一个方法作为参数,但没有传递它的类实例。
有两种修复方法:
- 将类实例绑定到你的参数上:
change(cubeClass.changeColour.bind(cubeClass));
- 更清晰的方式是提供一个包装函数,在其中定义了上下文:
change(() => cubeClass.changeColor());
英文:
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:
- bind the class instance to your argument:
change(cubeClass.changeColour.bind(cubeClass);
- a more cleaner way is to provide a wrapper function where the context is defined:
change(() => cubeClass.changeColor());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论