将类方法传递给函数参数以在函数内调用

huangapple go评论73阅读模式
英文:

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);

你传递了一个方法作为参数,但没有传递它的类实例。
有两种修复方法:

  1. 将类实例绑定到你的参数上:
change(cubeClass.changeColour.bind(cubeClass)); 
  1. 更清晰的方式是提供一个包装函数,在其中定义了上下文:
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:

  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());

huangapple
  • 本文由 发表于 2023年5月21日 16:49:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定