11_类中的访问类型和构造器!!!

类中的访问类型

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 允许在类内及继承的子类中使用

报错信息:
TypeScript

类中的构造器

  • 传统写法
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);
  • 结果:
    TypeScript

当然啦,大家如果有补充的或者其它问题,欢迎大家在评论区交流啊,路漫漫其修远兮,吾将上下而求索,希望大家可以一起坚持下去啊!😎😎😎~~~

TypeScript

如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续创作的动力 💪💪!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值