欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

typescript(三) 类的定义、继承、修饰符

程序员文章站 2022-07-03 23:18:29
...

(一)类的定义

class Person {
  name:string; // name string类型
  age:number; // age number类型
  constructor(name:string,age:number) {
    this.name = name;
    this.age = age;
  }
  print() {
    return this.name + this.age
  }
}

var p = new Person('zhouzhou', 18)
console.log(p.print())

(二)类的继承 extends 关键字

继承之后父元素有的全都有~比如一个Student继承Person

// 父类
class Person {
  name:string;
  age:number;
  constructor(name:string,age:number) {
    this.name = name;
    this.age = age;
  }
  print() {
    return this.name + this.age
  }
}

// 子类
class Students extends Person {
  cardNum:number; // 子类自己的属性
  school:string; // 子类自己的属性
  constructor(cardNum:number, school:string) {
    super('zhouzhou', 18) // super关键字 用来访问父类的构造函数 以及传入值
    this.cardNum = cardNum;
    this.school = school
  }
  homework () {
    return `${this.name} is ${this.age} years old, His cardNumber is ${this.cardNum}, his school is ${this.school}`
  }
}


var p = new Students(20655, '北京大学') // 传入子类需要的就好 父类的值通过super来传

console.log(p.homework())

打印结果:

zhouzhou is 18 years old, His cardNumber is 20655, his school is 北京大学

注:如果父类和子类有一些同名的方法,先执行自身的,如果自身没有,再去看看父类的~

(三)访问修饰符

访问修饰符有三类:public 、 private、protected

public:定义类的共有成员,任何人都可以进行访问,如果不加访问修饰符,则默认为public

private:定义类的私有成员,在类外不可以访问

protected: 受保护的 子类可以访问,其他类不可以访问

class Person {
  public name:string; // 公共的
  private age:number; // 私有的
  protected email:string; // 受保护的
  constructor (name:string, age:number, email:string) {
    this.name = name;
    this.age = age;
    this.email = email
  }
  print () {
    return `name: ${this.name}, age: ${this.age}, email: ${this.email}`
  }
}

var p = new Person('zhouzhou', 18, '[email protected]')
console.log(p.print()) // 类的内部访问 正常打印
console.log(p.name) // zhouzhou
console.log(p.age) // 报错 (类外访问)
console.log(p.email) // 报错 (类外访问)

(四)静态属性、静态方法

在js中:实例属性、实例方法、静态属性、静态方法

function Person () {
  // 实例属性
  this.name = 'name';
  // 实例方法
  this.print = function () {
    return `name: ${this.name}`
  }
}

// 静态方法
Person.add = function () { 
   console.log('add one')
}

// 静态属性
Person.age = 19

// 静态调用
Person.add()
console.log(Person.age)

// 实例的调用
var a = new Person()
console.log(a.name)
console.log(a.print())

在ts中~

class Person {
  // 实例属性
  static email:string;
  name:string;
  age:number;
  constructor(name:string, age:number, email:string) {
    this.name = name;
    this.age = age;
    // this.email = email
  }
  // 实例方法
  print () {
    return this.name + ',' + this.age
  }
  // 静态static修饰符 方法
  static show() {
    console.log('show')
  }
}
// 静态属性的调用
Person.email = '[email protected]'
console.log(Person.email)

// 静态方法的调用
Person.show()

// 实例的调用
var p = new Person('zhouzhou', 19, '197846795')
console.log(p.print())



如果方法不依赖于实例方法,即可定义成静态的~