MST

星途 面试题库

面试题:TypeScript中public、private、protected修饰符在类继承中的表现

请举例说明在TypeScript中,一个父类使用public、private、protected修饰的属性或方法,在子类继承时的访问权限分别是怎样的?
31.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. public 修饰符
    • 在父类中使用 public 修饰的属性或方法,子类可以自由访问。
    • 示例代码:
class Parent {
    public publicProperty: string;
    public publicMethod() {
        return 'This is a public method';
    }
    constructor() {
        this.publicProperty = 'Public property value';
    }
}

class Child extends Parent {
    accessPublic() {
        return this.publicProperty + ','+ this.publicMethod();
    }
}

const child = new Child();
console.log(child.accessPublic());
  1. private 修饰符
    • 在父类中使用 private 修饰的属性或方法,子类无法直接访问。
    • 示例代码:
class Parent {
    private privateProperty: string;
    private privateMethod() {
        return 'This is a private method';
    }
    constructor() {
        this.privateProperty = 'Private property value';
    }
}

class Child extends Parent {
    // 以下代码会报错,因为无法访问父类的私有成员
    // accessPrivate() {
    //     return this.privateProperty + ','+ this.privateMethod();
    // }
}
  1. protected 修饰符
    • 在父类中使用 protected 修饰的属性或方法,子类可以访问,但不能在类外部直接访问。
    • 示例代码:
class Parent {
    protected protectedProperty: string;
    protected protectedMethod() {
        return 'This is a protected method';
    }
    constructor() {
        this.protectedProperty = 'Protected property value';
    }
}

class Child extends Parent {
    accessProtected() {
        return this.protectedProperty + ','+ this.protectedMethod();
    }
}

const child = new Child();
console.log(child.accessProtected());
// 以下代码会报错,因为不能在类外部访问 protected 成员
// console.log(child.protectedProperty);
// console.log(child.protectedMethod());