- 类的方法修饰符和属性的修饰符一样,只不过方法的修饰符是没有
readonly
的
博主假设有这么一个需求: 有一个基类, 所有的子类都需要继承于这个基类, 但是我们不希望别人能够通过基类来创建对象:
错误示例:
class Person {
name: string;
age: number;
gender: string;
protected constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
say(): void {
console.log(`name=${this.name},age=${this.age},gender=${this.gender}`);
}
}
class Student extends Person {
constructor(name: string, age: number, gender: string) {
super(name, age, gender);
}
}
let p = new Person('BNTang', 18, 'male');
let stu = new Student('zs', 18, 'female');
正确示例:
class Person {
name: string;
age: number;
gender: string;
protected constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
say(): void {
console.log(`name=${this.name},age=${this.age},gender=${this.gender}`);
}
}
class Student extends Person {
constructor(name: string, age: number, gender: string) {
super(name, age, gender);
}
}
let stu = new Student('zs', 18, 'female');
console.log(stu);