首页 > 其他分享 >【鸿蒙】HarmonyOS NEXT星河入门到实战7-ArkTS语法进阶

【鸿蒙】HarmonyOS NEXT星河入门到实战7-ArkTS语法进阶

时间:2024-09-14 20:21:06浏览次数:3  
标签:ArkTS console name age 星河 number NEXT let string

目录

1、Class类

1.1 Class类 实例属性

1.2  Class类 构造函数

1.3 Class类 定义方法

1.4 静态属性 和 静态方法

1.5 继承 extends 和 super 关键字

1.6 instanceof 检测是否实例

1.7.修饰符(readonly、private、protected 、public)

1.7.1 readonly

1.7.2 Private 

 1.7.3 protected

 1.7.4 public

2、剩余参数和展开运算符

2.1 剩余参数语法

2.2 剩余参数和展开运算符

 3、接口补充

3.1 接口继承

3.2 接口实现

 4、泛型

4.1 泛型函数

4.2 泛型约束

4.3 多个泛型参数

 4.4 泛型接口

4.5 泛型类


前言: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

相关文章

  • 【鸿蒙】HarmonyOS NEXT星河入门到实战4-ArkTS界面布局深入
    目录一、布局元素组成1.1内边距-padding1.2外边距margin1.3实战案例-QQ音乐-登录1.4边框border 二、设置组件圆角2.1基本圆角设置2.2特殊形状的圆角设置三、背景属性3.1背景图片-backgroundImage3.2背景图片位置-backgroundImagePosition3.3背景定位-......
  • 【鸿蒙】HarmonyOS NEXT星河入门到实战5-基础语法
    目录一、字符串拼接1.1常规字符串拼接1.2模板字符串`hello`(符号在键盘的tab上面)二、类型转换(数字和字符串)2.1字符串转数字 2.2数字转字符串三、交互3.1点击事件3.2状态管理 3.3计数器案例四、运算符4.1算数运算符 4.2赋值运算符4.3点赞案例  ......
  • vite tailwindcss@next omi
    pnpmi@tailwindcss/vite@[email protected]:{ "type":"module", "dependencies":{ "@tailwindcss/vite":"4.0.0-alpha.24", "omi":"^7.7.0", "tailwi......
  • 零基础快速上手HarmonyOS ArkTS开发5---从简单的页面开始2---使用List组件构建列表、G
    接着继续往下学习页面布局的知识。最近发现之前学习这一章节的内容在官方已经被下了,替换成了另外一个案例了(https://developer.huawei.com/consumer/cn/training/course/slightMooc/C101717497398588123):而且整个视频的风格也不一样了,先看看之前的这个美女讲师:再看看现在的:哇塞,档次......
  • i18next
    i18next23.15.1 • Public • Published 3daysago ReadmeCode Beta1Dependency6,345Dependents497Versionsi18next:learnonce-translateeverywhere       i18nextisaverypopularinternationalizationframeworkforbrowseroran......
  • 生成器yield,next()与send()
    #把a创建成了一个生成器对象generatorobjecta=(x*2forxinrange(10))print(a)print(next(a))#生成器对象调用用next(a),等价于a.__next__(),生成器一次调用一个print(next(a))foriina:#生成器是一个可迭代对象print(i)#创建生成器的第二种方式......
  • 深入浅出ASPvNext开源框架学习视频
    学习目标:从入门到深度剖析.NetCoreABPvNext学习内容:源码目录结构依赖关系及内容ABPvNext第一课:源码目录结构依赖关系及内容DDD理论知识及代码实现ABPvNext第二课:DDD理论知识及代码实现ABP启动流程及模块化深入ABPvNext第三课:ABP启动流程及模块化深入深入动态API......
  • nextTick 使用场景
    nextTick是Vue.js中的重要方法,用于在DOM更新后执行某些操作。它通常用于确保在数据变化后,视图已经更新完成,然后再进行某些操作(例如操作DOM、执行依赖于DOM的逻辑等)。以下是一些常见的使用场景:1.DOM操作有时你需要在数据变化后立即对DOM进行操作,如获取元素的尺寸或位......
  • convnext_xxlarge.clip_laion2b_soup_ft_in12k timm模型库
    Modelcardforconvnext_xxlarge.clip_laion2b_soup_ft_in12kAConvNeXtimageclassificationmodel.CLIPimagetowerweightspretrainedin OpenCLIP onLAIONandfine-tunedonImageNet-12kbyRossWightman.PleaseseerelatedOpenCLIPmodelcardsformored......
  • 鸿蒙HarmonyOS Next应用开发实战学习路线
    ✍️作者简介:小北编程(专注于HarmonyOS、Android、Java、Web、TCP/IP等技术方向)......