直接上代码
通过传递两个不同参数类型来求面积实现
不理解的话,可以看TS函数重载
type areaType = {
width: number,
height: number
}
class Squar {
public width
public height
constructor(width_:number, height_:number)
constructor(valueObj: areaType)
constructor(public objWidth_: any, public height_: number = 1) {
if(typeof objWidth_ === "object") {
this.width = objWidth_.width
this.height = objWidth_.height
} else {
this.width = objWidth_
this.height = height_
}
}
getArea() {
return this.width * this.height
}
}
let p = new Squar(40, 50)
console.log(p.getArea());
let s = new Squar({width: 10, height: 10})
console.log(s.getArea());