目录
1.7.修饰符(readonly、private、protected 、public)
前言:ArkTS语法进阶Class、剩余参数和展开运算符,同时包含对接口的补充说明、泛型
1、Class类
1.1 Class类 实例属性
注意定义类要设置初始值,不设置初始值要设置为可选字段 使用符号?
import window from '@ohos.window';
class Cat {
name: string = 'Tom'
foods?: string
}
// 基于类创建对象
let p: Cat = new Cat()
p.foods = 'sss'
console.log(p.name)
@Entry
@Component
struct Index {
@State message: string = '@春天的菠菜';
onPageShow(): void {
window.getLastWindow(AppStorage.get("context"), (err, data) => {
if (err.code) {
console.error('Failed to get last window. Cause:' + JSON.stringify(err));
return;
}
data.setFullScreen(true)
});
}
build() {
Column(){
Text(p.name +'****'+ p.foods+'****'+ p.foods?.length)
.fontSize(20)
.fontWeight(700)
.backgroundColor(Color.Green)
.padding(10)
}
.width('100%').height(100)
}
}
1.2 Class类 构造函数
import window from '@ohos.window';
@Extend(Text)
function textExtend(){
.fontSize(20)
.fontWeight(700)
.backgroundColor(Color.Green)
.padding(10)
.margin(5)
}
// 1 构造函数语法
class Food {
name: string
price: number
constructor(name:string, price:number) {
this.name = name
this.price = price
}
}
let f1 = new Food('西红柿', 2.23)
let f2= new Food('面条', 15.00)
//********************************************************
interface iCat{
name: string
price: number
desc: string
}
// 多参数传参合并
class Cat {
name: string
price: number
desc: string
constructor(paramsObj: iCat) {
this.name = paramsObj.name
this.price = paramsObj.price
this.desc = paramsObj.desc
}
}
let p1: Cat = new Cat({
name: '波斯猫',
desc: '珀斯的猫',
price: 123222
})
@Entry
@Component
struct Index {
@State message: string = '@春天的菠菜';
onPageShow(): void {
window.getLastWindow(AppStorage.get("context"), (err, data) => {
if (err.code) {
console.error('Failed to get last window. Cause:' + JSON.stringify(err));
return;
}
data.setFullScreen(true)
});
}
build() {
Column(){
Text(f1.name +'****'+ f1.price+'元')
.textExtend()
Text(f2.name +'****'+ f2.price+'元')
.textExtend()
Text(p1.name +'****'+ p1.price+'元'+'****'+p1.desc)
.textExtend()
}
.width('100%').height(100)
}
}
1.3 Class类 定义方法
import window from '@ohos.window';
@Extend(Text)
function textExtend(){
.fontSize(20)
.fontWeight(700)
.backgroundColor(Color.Green)
.padding(10)
.margin(5)
}
class Person {
name: string
age: number
constructor(name: string,age: number) {
this.name = name
this.age = age
}
// 类方法
sayHi(yorName:string){
return ('Hello!' + yorName + '我是' + this.name)
}
}
let p1: Person = new Person('波斯猫', 18)
@Entry
@Component
struct Index {
@State message: string = '@春天的菠菜';
onPageShow(): void {
window.getLastWindow(AppStorage.get("context"), (err, data) => {
if (err.code) {
console.error('Failed to get last window. Cause:' + JSON.stringify(err));
return;
}
data.setFullScreen(true)
});
}
build() {
Column(){
Text(p1.name +'****'+ p1.sayHi('春天的菠菜'))
.textExtend()
}
.width('100%').height(100)
}
}
1.4 静态属性 和 静态方法
import window from '@ohos.window';
@Extend(Text)
function textExtend(){
.fontSize(20)
.fontWeight(700)
.backgroundColor(Color.Green)
.padding(10)
.margin(5)
}
class Robot {
static version: string = 'V2.0'
static getRandom():number{
return Math.random()
}
}
@Entry
@Component
struct Index {
@State message: string = '@春天的菠菜';
onPageShow(): void {
window.getLastWindow(AppStorage.get("context"), (err, data) => {
if (err.code) {
console.error('Failed to get last window. Cause:' + JSON.stringify(err));
return;
}
data.setFullScreen(true)
});
}
build() {
Column(){
Text(Robot.version +'****'+ Robot.getRandom())
.textExtend()
}
.width('100%').height(100)
}
}
1.5 继承 extends 和 super 关键字
import window from '@ohos.window';
@Extend(Text)
function textExtend(){
.fontSize(20)
.fontWeight(700)
.backgroundColor(Color.Green)
.padding(10)
.margin(5)
}
class Person {
name: string
age: number
constructor(name:string, age:number) {
this.name =name
this.age = age
}
sayHi(): string{
return 'Hello!'
}
}
class Student extends Person{
grade: string
constructor(name:string, age:number,grade: string) {
// 父类中的构造函数
super(name,age)
this.grade = grade
}
// 子类想要重写父类的方法,只需提供同名的方法即可
sayHi(): string{
super.sayHi() // 保留了父类的,又新增了自己的
return 'Student HI!'
}
study (): string {
return '我爱学习'
}
}
class Teacher extends Person{
}
class Worker extends Person{
}
let s1: Student = new Student('张三',18,'五年级')
let t1: Teacher = new Teacher('李四',32)
let w1: Worker = new Worker('王五', 46)
@Entry
@Component
struct Index {
@State message: string = '@春天的菠菜';
onPageShow(): void {
window.getLastWindow(AppStorage.get("context"), (err, data) => {
if (err.code) {
console.error('Failed to get last window. Cause:' + JSON.stringify(err));
return;
}
data.setFullScreen(true)
});
}
build() {
Column(){
Text( s1.name+ s1.sayHi()+s1.grade+s1.study()+'****'+ t1.name+t1.sayHi())
.textExtend()
}
.width('100%').height(100)
}
}
1.6 instanceof 检测是否实例
// console.log(typeof 111)
// console.log(typeof true)
// console.log(typeof 'abc')
//
// // typeof 仅能用于判断简单类型, 复杂类型需要用instanceof判断
// class Person {}
// class Student {}
// let p: Person = new Person()
// let s: Student = new Student()
// console.log(typeof p)
// console.log(typeof s)
class Person {}
class Student extends Person {}
class Worker extends Person {}
let s: Student = new Student()
console.log('判断结果:', s instanceof Student)
console.log('判断结果:', s instanceof Person)
console.log('判断结果:', s instanceof Worker)
interface IObj {}
// 判断一个变量是否存的是数组
let temp: IObj = {}
console.log('是否是数组', temp instanceof Array)
@Entry
@Component
struct Index {
build() {
// Row().width(100)
Column() {
}
}
}
1.7.修饰符(readonly、private、protected 、public)
1.7.1 readonly
// 修饰符 readonly
class Cat {
name: string
age: number
readonly legs: number = 4
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
let c1 = new Cat('小花', 2)
c1.name = '小美'
// c1.legs = 6 // 不能修改
console.log('姓名:', c1.name)
// 3.1415926 圆周率
// Math.PI
@Entry
@Component
struct Index {
build() {
// Row().width(100)
Column() {
}
}
}
1.7.2 Private
// class Person {
// private name: string = ''
// private age: number = 0
// desc: string = '描述'
// }
// let p = new Person()
// console.log('实例访问:', p.name) // 无法再外部访问私有数据
// class Student extends Person {
// sayHi () {
// console.log('访问私有的数据:', super.name) // 私有数据无法再(子类)访问
// }
// }
@Entry
@Component
struct Index {
build() {
// Row().width(100)
Column() {
}
}
}
1.7.3 protected
1.7.4 public
class Person {
protected name: string
protected age: number
desc: string = '描述'
// 类的内容, 无论是私有还是保护, 都是可以访问的
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
let p = new Person('小王', 18)
// console.log('实例访问:', p.name) // 无法在外部, 访问受保护的数据
class Student extends Person {
sayHi () {
console.log('访问私有的数据:', super.name) // 保护的数据可以在子类访问
}
}
@Entry
@Component
struct Index {
build() {
// Row().width(100)
Column() {
}
}
}
2、剩余参数和展开运算符
2.1 剩余参数语法
// ... 展开运算符, 用于数组的平铺合并
let arr1: number[] = [1,2,3]
let arr2: number[] = [4,5,6]
let newArr: number[] = [...arr1, ...arr2]
console.log('最终的数组', newArr)
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
2.2 剩余参数和展开运算符
合并数组
// ... 展开运算符, 用于数组的平铺合并
let arr1: number[] = [1,2,3]
let arr2: number[] = [4,5,6]
let newArr: number[] = [...arr1, ...arr2]
console.log('最终的数组', newArr)
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
3、接口补充
3.1 接口继承
interface IAnimal {
name: string
age: number
}
interface ICat extends IAnimal {
hair: string
}
interface IDog extends IAnimal {
color: string
}
let dog1: IDog = {
name: '小泰迪',
age: 2,
color: '棕色'
}
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
3.2 接口实现
// 接口实现: 定义一个接口, 约束类 => 类需要按照接口的要求, 实现类的主体
interface IDog {
name: string
age: number
jump: () => void
}
// 基于接口, 实现类
class Dog implements IDog {
name: string
age: number
desc: string
constructor(name: string, age: number, desc: string) {
this.name = name
this.age = age
this.desc = desc
}
jump() {
}
}
let dog: Dog = new Dog('小飞', 2, '是一只非常帅气的二哈')
dog.jump()
function 函数名<Type>(temp:Type):Type{
return temp
}
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
4、泛型
4.1 泛型函数
// 泛型: 广泛的类型 => 类型可以作为参数传递过来, 类型是[可变]的
// function 函数名<Type> (形参: Type): Type {
// return 形参
// }
// 封装了一个函数: 传入什么样的参数, 就立刻返回什么样的参数
function fn<T> (param: T) : T {
return param
}
fn<string>('abc')
fn<number>(123)
fn<boolean>(true)
fn<number[]>([1, 2, 3, 4, 5])
// 会默认根据传参, 进行类型推断, 动态的配置 T 类型参数 的值
fn(true)
fn([1, 2, 3, 4, 5])
// 练习1: 定义函数, 参数是数组(存的类型不定), 返回数组的长度
function getLength<T> (arr: T[]) : number {
return arr.length
}
console.log('', getLength<number>([1, 2, 3]))
console.log('', getLength<string>(['1', 'aa', 'bb', 'cc']))
// 练习2: 定义函数, 参数是数组(存的类型不定), 返回数组的最后一项
function getLast<T> (arr: T[]) : T {
return arr[arr.length - 1]
}
console.log('', getLast<number>([1, 2, 3, 4, 99]))
console.log('', getLast<string>(['a', 'b', 'c']))
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
4.2 泛型约束
// 泛型约束: 给传递的类型参数, 添加限制
interface ILength {
length: number
}
function fn<T extends ILength>(param: T) {
console.log('', param.length)
}
fn<string>('abc')
fn<number[]>([1, 2, 3])
class Desk {
length = 2
}
let d = new Desk()
fn<Desk>(d)
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
4.3 多个泛型参数
// 多个泛型变量 => 传递多个类型参数
function fn<T1, T2> (param1: T1, param2: T2) {
console.log('参数1', param1)
console.log('参数2', param2)
}
fn<string, boolean>('abc', true)
fn<number, string>(123, 'abc')
fn<string[], number[]>(['a', 'b'], [1, 2])
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
新版本已经能自动识别
4.4 泛型接口
// 泛型接口
interface IdFunc<T> {
// 约定有两个方法 (id类型不定, string number)
// 1. 传入 id 值, 就返回 id 值
// 2. 返回一个 ids 数组
id: (value: T) => T
ids: () => T[]
}
let obj: IdFunc<number> = {
id(value: number) {
return value
},
ids() {
return [1, 2, 3]
}
}
let obj2: IdFunc<string> = {
id(value: string) {
return value
},
ids() {
return ['001', '002', '003']
}
}
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
4.5 泛型类
// 泛型类: 定义类的时候, 配合泛型一起定义
class Person <T>{
id: T
constructor(id: T) {
this.id = id
}
getId (): T {
return this.id
}
}
let p: Person<number> = new Person<number>(10)
let p2: Person<string> = new Person<string>('abc')
@Entry
@Component
struct Index {
build() {
Column() {
}
}
}
标签:ArkTS,console,name,age,星河,number,NEXT,let,string
From: https://blog.csdn.net/legend818/article/details/142176092