鸿蒙学习笔记
第十二节 鸿蒙前置知识补充TS中的对象
语法于java比较相似
//定义枚举
enum Msg{
//与java枚举类似都是公开常量
HI = 'Hi'
HELLO = 'hello'
}
//定义接口抽象方法接受参数
interface A{
say(msg:Msg):void
}
//定义类实现接口
class B implements A{
say(msg:Msg):void{
console.log(msg+"i am B")
}
}
let a = new B()
a.say(Msg.HI)
-----------------------------------------------------
class Rectangle {
private width:number
private length:number
constructor(width:number,length:number){
this.width = width
this.length = length
}
public area():number{
return this.width*this.height
}
}
class Square extends Rectangle{
constructor(size:number){
super(size,size)
}
}
let s = new Square(5);
console.log(s.area())
----------------------------------------------
应用复杂的时候可以把通用功能抽取到单独的ts文件中,
每个文件是一个模块,模块之间可以相互加载
//定义矩形类
export class Rectangle {
public width:number
public length:number
constructor(width:number,length:number){
this.width = width
this.length = length
}
}
export function area(rec:Rectangle):number{
return rec.width*rec.length
}
----
另外一个类
import {Rectangle,area} from '.../rectangle'
let r = new Rectangle(10,20)
console.log(area(r))