在当今的应用开发中,TypeScript凭借其静态类型和面向对象编程的特性,成为了越来越多开发者的首选语言。而在鸿蒙原生应用开发中,掌握TypeScript中的类的使用,不仅能提升我们的开发效率,还能帮助我们构建更加稳健和可维护的应用程序。
本文将重点介绍TypeScript中的类的基本概念和高级特性,从类的定义、构造函数,到继承、多态等内容,逐步带领你深入理解面向对象编程的思想。通过实际案例,我们将展示如何在鸿蒙原生应用中灵活运用类,提高代码的复用性和可读性。
function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype.type = '动物';
Cat.prototype.eat = function() {
console.log("吃老鼠");
};
var cat1 = new Cat("大明", "黄色");
new
关键字实例化对象class Cat2 {
name: string; // TypeScript 类型声明
color: string;
constructor(name: string, color: string) {
this.name = name;
this.color = color;
}
eat() {
console.log("吃老鼠");
}
sayName(): string {
return `My name is ${this.name}`;
}
}
const cat3 = new Cat2("小小明", "黑色");
class
为语法糖,本质仍为原型链function
关键字class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
eat(): string {
return "吃骨头";
}
}
class Dog extends Animal {
constructor(name: string) {
super(name); // 必须调用父类构造函数
}
sayHi(): string {
return `${this.name}, ${this.eat()}`;
}
}
const d = new Dog('Tom');
console.log(d.sayHi()); // "Tom, 吃骨头"
extends
实现继承super()
必须在使用 this
前调用修饰符 | 访问范围 |
---|---|
public | 默认,任意位置可访问 |
private | 仅类内部可访问 |
protected | 类内部及子类可访问 |
class Animal3 {
public name: string;
constructor(name: string) {
this.name = name;
}
}
class Animal4 {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Animal5 {
name: string;
constructor(name: string) {
this.name = name;
}
sayHi(): string {
return `My name is ${this.name}`;
}
}
let s4: Animal5 = new Animal5('Jack');
console.log(s4.sayHi());
interface Animal6 {
name: string;
action(): string;
}
class Dog2 implements Animal6 {
name: string;
constructor(name: string) {
this.name = name;
}
action(): string {
return '摇尾巴';
}
}
interface Alarm {
alert(): void;
}
interface Light {
lightOn(): void;
lightOff(): void;
}
class Car implements Alarm, Light {
alert() {
console.log('警报声');
}
lightOn() {
console.log('开灯');
}
lightOff() {
console.log('关灯');
}
}
门
类与 车
类都可实现 报警
接口特性 | 传统方式 | ES6 Class |
---|---|---|
构造函数 | function 函数 | constructor 方法 |
方法定义 | 需通过原型添加 | 类内直接定义 |
继承 | 手动操作原型链 | extends 关键字 |
代码可读性 | 较低 | 接近传统 OOP 语法 |
this
指向实例对象private
/protected
为 TypeScript 特性