HarmonyOS NEXT鸿蒙开发 ArkTS:class类

说明

class 类,与 java中的写法很类似

  • class 关键字定义了类
  • constructor 方法是构造方法
  • new 通过 new constructor() 创建对象
  • this 关键字代表实例对象
  • extends 关键字表示继承某个类
  • super() 调用父类构造方法

定义类

class 类名{

}

例子

class Phone{

}
class Student{

}

创建对象

通过定义好的类,创建对象:

const iphone13 = new Phone()

const huawei = new Phone()
const lilei = new Student()


const hanmeimei = new Student()

定义属性

根据同一张图纸生成的手机,虽然一模一样,但有些部分是不同的,比如:手机序列号

用户买回后,又给手机进行自定义设置,如:手机名、wifi名 等

这些就是 属性

class 类名{
    属性1 : 类型 = 值1
    属性2 = 值2 // 类型可省略,根据初始值自动推论
}

例子1

在类中定义属性:

class Phone{
    name:string = 'iphone13'
    sn = '123' // 类型可省略,根据初始值自动推论 sn 是 string类型
}

通过实例对象访问属性:

const iphone = new Phone()
console.log(iphone.name)
console.log(iphone.sn)

例子2

class Student{
    age:number = 20
    sex = '男' // 类型可省略,根据初始值自动推论 sex 是 string类型
}

通过实例对象访问属性:

const lilei = new Student()

console.log(lilei.age)
console.log(lilei.sex)

构造函数

作用:给实例属性初始值

constructor(形参1:类型1,形参1:类型1){

}

解释:

  • 构造函数名是 constructor
  • 没有返回值,也不能写 :void,否则报错

例子1

定义类:

class Phone{
    name:string // 在这里声明属性,否则报错
    sn:string
    // 构造函数有形参
    constructor(name:string,sn:string){
            this.name = name
            this.sn = sn
        }
}

创建对象时,是通过构造函数,要传参:

const nokia = new Phone("李雷的手机","123")
console.log(nokia.name)
console.log(nokia.sn)

const iphone = new Phone("韩梅梅的手机","456")
console.log(iphone.name)
console.log(iphone.sn)

例子2

定义类:

class Student{
    name:string
    age:number = 20
    sex = '男' // 自定推断出 sex 是 string类型

    constructor(name:string,age:number,sex:string){
        this.name = name
        this.age = age
        this.sex = sex
    }
}

使用该类创建对象:

const lilei = new Student("李雷",20,'男')
const hanmeimei = new Student("韩梅梅",19,'女')

console.log(lilei.name)
console.log(lilei.age)
console.log(lilei.sex)

console.log(hanmeimei.name)
console.log(hanmeimei.age)
console.log(hanmeimei.sex)

实例方法

函数的缺点

像下面这些函数,数量多了,就会混乱

// 函数 “吃”
function eat(){

}

// 函数 “打电话”
function call(){

}
解决

将函数放入到类中

实例方法的介绍

将函数放入到类中,就是 方法

作用:更好的封装,如:将 eat() 放入到 Student 类中,将 call() 放入到 Phone 类中,更加清晰

例子

class Phone{
    // 打电话
    call(number:string) : void {
        console.log("打电话给:",number)
    }
    // 手机支持计算器的加法运算
    add(a:number , b:number) : number {
        return a + b
    }
}

const nokia = new Phone()
nokia.call( "110" )
const res = nokia.add(1,2)
console.log(res)

原文出处:/show_1GW1xj9Rf6GF.html