day170-TypeScript基础小记-参数属性

要点

  1. 存取器。
  2. 静态属性。

存取器

例子1

把简单的类改写成使用getset
注意:只带get不带有set的存取器自动被推断为readonly

// 随意修改全名
class Employee {
fullName: string
}
let employee = new Employee()
employee.fullName = '二柱子'
if (employee.fullName) {
console.log(employee.fullName)
}
// 加密,不让随意修改全名
let passcode = 'secret passcode'
class Employee {
private _fullName: string
get fullName (): string {
return this._fullName
}
set fullName (newName: string) {
if (passcode && passcode == 'secret passcode') {
this._fullName = newName
} else {
console.log('Error: 认证错误!又想把人名字改成二柱子!')
}
}
}
let employee = new Employee()
employee.fullName = "铁蛋"
if (employee.fullName) {
console.log(employee.fullName)
}

静态属性

  1. 这些属性存在类本身上而不是类的实例上。
  2. 例子1

    使用static定义origin,因为origin是所有网格都会用到的属性。每个实例访问该属性时,都要在origin前面加上类名。
    如同在实例属性上使用this.前缀来访问属性,本例子用Grid.来访问静态属性

class Grid {
static origin = { x: 0, y: 0 }
constructor (public scale: number) {}
calculateDistanceFromOrigin (point: { x: number, y: number }) {
let xDis = (point.x - Grid.origin.x)
let yDis = (point.y - Grid.origin.y)
return Math.sqrt(xDis * xDis + yDis * yDis) / this.scale
}
}
let grid1 = new Grid(1.0)
let grid2 = new Grid(2.0)
console.log(grid1.calculateDistanceFromOrigin({x: 1, y: 1}))
console.log(grid2.calculateDistanceFromOrigin({x: 2, y: 2}))
文章作者: lmislm
文章链接: http://lmislm.com/2019/07/02/2019-07-02/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog