简体   繁体   English

如何从对象内部调用类函数?

[英]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. 我不能使用this ,因为它是指对象而不是类。 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 ? 如何从objectFunction内部调用functionA

You can simply set another variable (eg, self ) equal to this prior to this changing. 你可以简单地设置另一个变量(例如, self )等于this之前, this变化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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