类中的访问类型
private, protected, public 三种访问类型
class Person {
protected name: string;
public sayHi() {
this.name = "ws";
console.log(this.name);
console.log("hi");
}
private sayABC() {
this.name;
}
}
class Teacher extends Person {
public sayBye() {
this.sayHi();
}
}
const person = new Person();
person.name = 'dell';
console.log(person.name);
person.sayHi();
小结
public 允许我在类的内外被调用
private 允许在类内被使用
protected 允许在类内及继承的子类中使用
报错信息:
类中的构造器
- 传统写法
class Person {
//
public name: string;
constructor(name: string) {
this.name = name;
}
// constructor(public name: string) {}
}
const person = new Person("dell");
console.log(person.name);
- 简化写法
class Person {
constructor(public name: string) {}
}
const person = new Person("dell");
console.log(person.name);
调用父类的构造器
class Person {
constructor(public name: string) {}
}
class Teacher extends Person {
constructor(public age: number) {
super("dell");
}
}
测试及结果
- 测试代码:
const teacher = new Teacher(28);
console.log(teacher.age);
console.log(teacher.name);
- 结果:
当然啦,大家如果有补充的或者其它问题,欢迎大家在评论区交流啊,路漫漫其修远兮,吾将上下而求索,希望大家可以一起坚持下去啊!😎😎😎~~~
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续创作的动力 💪💪!!!