首页 > 解决方案 > 在 ES6 类方法中,如何确保“this”始终指向类本身,而不是子类?

问题描述

例如:

class Parent {
    func1() {
        console.log("I am func1, in class Parent");
    }

    func2() {
        this.func1();
    }
}

class Child extends Parent {
    func1() {
        console.log("I am func1, in class Child");
    }
}

let a = new Child();
a.func2();

因为“this”在调用a.func2()时指向Child,所以会输出“I am func1, in class Child”。

但是现在我希望 Parent.func2() 在任何情况下始终调用 Parent.func1(),即使“this”与 Child 绑定,我该怎么做?

我试过了

func2() {
    super.func1();
}

显然当 Parent 调用 func2() 时它不能工作:

let b = new Parent();
b.func2(); //not work

我想要这样的东西:

class Parent {
    func1() {
        console.log("I am func1, in class Parent");
    }

    func2() {
        Parent.func1(); //always access Parent.func1() even if func1() is overrode. 
    }
}

请帮忙。

标签: javascript

解决方案


没有特殊的语法,您需要明确引用您要准确调用的方法:

class Parent {
    func1() {
        console.log("I am func1, in class Parent");
    }

    func2() {
        Parent.prototype.func1.call(this);
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
}

推荐阅读