加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

TypeScript 类(Class)教程

发布时间:2023-03-30 08:53:06 所属栏目:教程 来源:
导读:自 ES6 起,终于迎来了 class,对于开发者来说,终于可以使用基于类的面向对象式编程。TypeScript 在原 ES6 中类的基础上,还添加了一些新的功能,比如几种访问修饰符,这是在其他面向对象语言中早就实现了的。

J
自 ES6 起,终于迎来了 class,对于开发者来说,终于可以使用基于类的面向对象式编程。TypeScript 在原 ES6 中类的基础上,还添加了一些新的功能,比如几种访问修饰符,这是在其他面向对象语言中早就实现了的。

JavaScript 的类作为语法糖,我们不但需要知道怎么去使用,还应该了解其本质,涉及到原型的部分希望大家能深入理解。

类描述了所创建的对象共同的属性和方法。通过 class 关键字声明一个类,主要包含以下模块:

属性
构造函数
方法

JavaScript 中,生成实例对象可以通过构造函数的方式:

function Calculate (x, y) {
  this.x = x
  this.y = y
}
Calculate.prototype.add = function () {
  return this.x + this.y
}
var calculate = new Calculate(, )
console.log(calculate.add()) // 3
如果通过 class 关键字进行改写:

class Calculate {
  // 类的属性
  public x: number
  public y: number
  // 构造函数
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
  // 类的方法
  add () {
    return this.x + this.y
  }
}
const calculate = new Calculate(, )
console.log(calculate.add()) // 3
console.log(typeof Calculate) // 'function'
console.log(Calculate === Calculate.prototype.constructor) // true
代码解释:

最后一行,可以看出,类指向其构造函数本身,class 关键字可以看做是一个语法糖。

constructor() 方法是类的默认方法,通过 new 来生成对象实例时,自动调用该方法。换句话说,constructor() 方法默认返回实例对象 this。

基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类,这样可以抽出公共部分让子类复用。

使用 extends 关键字来实现继承:

// 继承 JavaScript 内置的 Date 对象
class LinDate extends Date {
  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}
const date = new LinDate()
console.log(date.getFullYear());     // 2020
console.log(date.getFormattedDate()) // 7-Jan-2020
代码解释: LinDate 继承了 Date 的功能,可以使用父类 Date 的方法 getFullYear(),也可以使用自身的方法 getFormattedDate()。

子类在 constructor 内中使用 super() 方法调用父类的构造函数,在一般方法内使用 super.method() 执行父类的方法。

class Animal {
  public name:string
  constructor(name: string) { 
    this.name = name 
  }
  move(distance: number = ) {
      console.log(`${this.name} moved ${distance}m.`)
  }
}
class Dog extends Animal {
  constructor(name: string) { 
    // 调用父类的构造函数
    super(name)
  }
  move(distance = ) {
      console.log('bark...')
      // 执行父类的方法
      super.move(distance) 
  }
}
const dog: Animal = new Dog('Coco')
dog.move() // Coco moved 10m.
代码解释:

第 16 行,通过 super() 调用了父类的构造函数。

第 22 行,通过 super 关键字调用父类的方法。

TypeScript 可以使用四种访问修饰符 public、protected、private 和 readonly。

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章