对象方法

方法作用:描述对象的具体行为

  1. 约定方法类型
interface 接口名称 {
方法名: (参数:类型) => 返回值类型
}
 interface Person{
 dance: () => void
 sing: (song: string) => void
 }
  1. 添加方法(箭头函数)
let ym: Person = {
 dance: () => {
 console.log('杨幂说', '我来跳个舞')
 },
 sing: (song: string) => {
 console.log('杨幂说', '我来唱首', song)
 }
 }
 ym.dance()
 ym.sing('爱的供养')
对象名.方法名(实参)

实例

// 需求:定义一个对象
// 特征:姓名:杨幂  年纪:18  体重:90
// 行为:唱歌、跳舞

// 1. 定义接口
interface Person {
  name: string
  age: number
  weight: number

  // ① 定义方法的类型
  sing: (song: string) => void
  dance: () => void
}

// 2. 基于接口,定义对象
let ym: Person = {
  name: '大幂幂',
  age: 18,
  weight: 90,

  // ② 定义方法
  sing: (song: string) => {
    console.log('杨幂说', '我来唱首歌', song)
  },
  dance: () => {
    console.log('杨幂说', '我来跳个舞')
  }
}

// ③ 调用对象里面的方法 (重要!!)
ym.sing('爱的供养')
ym.dance()


@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

在这里插入图片描述

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐