简体   繁体   中英

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 ?

You can simply set another variable (eg, 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();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM