dieortin
dieortin

Reputation: 522

How can I call a class function from inside an Object?

I'm trying to call a class' function from inside an object stored in another function of the same class. I can't use this, as it refers to the object and not to the class. Directly calling the function by its name doesn't work either, as it throws a "not defined" error.

I have code equivalent to this:

class X extends Y {
    functionA() {
        console.log("Function called!");
    }
    functionB() {
        window.testObject = {
            objectFunction() {
                // I need to call functionA from inside here
            }
        }
    }
}

How can I call functionA from inside objectFunction?

Upvotes: 0

Views: 37

Answers (1)

Nick
Nick

Reputation: 16576

You can simply set another variable (e.g., self) equal to this prior to this changing.

class X extends Y {
    functionA() {
        console.log("Function called!");
    }
    functionB() {
        let self = this;
        window.testObject = {
            objectFunction() {
                // I need to call functionA from inside here
                self.functionA();
            }
        }
    }
}

Upvotes: 3

Related Questions