对象:是一个可以储存多个数据的容器

构建一个employee的类对象,将共用属性行为写出

不会报错方式一:将其初始化

class Employee{
  name:string = ' '
  sex:string = ' '
  sal:number = 0
  comn: number = 0
}

方法二:构造方法,只能写一个,不能有多个

class Employee {
  name: string
  sex: string
  sal: number
  comm: number

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

行为:方法,函数

show(){
 console.log('ken',this.name,this.sex,this.sal,this.comm) 
}

getIncome() {
  return this.sal + this.comm
}

对象的创建:

  new 类名() 不在同一个文件夹下面:我们需要进行导入和导出

export class Employee { //将要导出的类添加export
import {Employee} from '../common/Employee'


@Entry
@Component
struct ObjectDemoPage {

  build(){
    Column(){
      Button('对象测试1').onClick(()=>{
        //emp就是一个对象,可以使用,去访问对象中的属性和行为
        let emp = new emp('阿牛','男',8000,0)

        emp.show()
        console.log('ken','收入',emp.getIncome())
      })
    }
  }

}

对象的测试:有三个访问修饰符,private,protected,public

默认公有,将其私有化

/common/employee.ets
private sal: number
getSal(){
  if(...){

  }
  return this.sal
}

/index.ets

getSal(){

 if(...){
}

 return this.sal

}

要赋予一个初始化一定要有类

export class Ball{
   size:number = 0
   name:string = ' '
}
let ball:Ball = {size:10,name:'羽毛球'}

如果说构造方法,则不能这么写,要设置一个变量存储。

Logo

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

更多推荐