在 TypeScript 中,private 方法只能在定义该方法的类内部访问,不能在子类中访问。子类只能访问父类中的公共方法和受保护方法,而不能访问父类中的私有方法。

以下是一个示例:

class ParentClass {
    private privateMethod() {
        console.log("This is a private method.");
    }

    protected protectedMethod() {
        console.log("This is a protected method.");
    }
}

class ChildClass extends ParentClass {
    public accessPrivateMethod() {
        // Error: 无法在子类中访问父类的私有方法
        this.privateMethod();
    }

    public accessProtectedMethod() {
        // 可以在子类中访问父类的受保护方法
        this.protectedMethod();
    }
}

const child = new ChildClass();
child.accessProtectedMethod(); // 输出: "This is a protected method."

在上面的示例中,ParentClass 中的 privateMethod 是私有方法,无法在 ChildClass 中访问,会导致编译错误。而 protectedMethod 是受保护方法,可以在子类中访问

typescript 类的private方法在子类中能否访问

原文地址: https://www.cveoy.top/t/topic/hPVw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录