Home > Software design >  JavaScript Send a object method as a parameter
JavaScript Send a object method as a parameter

Time:09-13

I am trying to send a method of a class to a function, so that this method goes into an infinite loop, how should I do it?

class MyClass {
    MyProperty;
    constructor() {
        this.MyProperty = "Some value";
    }
    MyMethod() {
        console.log(this.MyProperty);
        MyFunction(this.MyMethod);
    }
}

function MyFunction(MyParameter){
    MyParameter();
}

let Test = new MyClass()
Test.MyMethod()

CodePudding user response:

class MyClass {
    constructor() {
        this.MyProperty = "Some value";
    }
    MyMethod() {
        console.log(this.MyProperty);
        MyFunction(this.MyMethod.bind(this)); // <<--
    }
}
  • Related