TypeScript访问修饰符 -- public、private、protected
Access Modifier 访问修饰符
-
public
:默认都为公开的 public-
interface IPoint{ x:number; y:number; drawoPoint:() => void; getDistances:(p:IPoint) => number; } class Point implements IPoint{ // 在构造器中对变量加上 public 修饰符 // 就不用单独定义变量 constructor(public x:number,public y:number){ this.x = x; this.y = y; } public drawoPoint= () => { console.log('x',this.x,'y',this.y) }; // 默认为都为 public getDistances= (p: IPoint)=>{ return p.y } }
-
-
private
:不能直接访问 private 修饰的内容-
getter 方法以关键字
get
开头 -
setter 方法以关键字
set
开头 -
interface IPoint{ // getter setter setY:number; getY:number; drawoPoint:() => void; getDistances:(p:IPoint) => number; } class Point implements IPoint{ // private 修饰的变量、方法 要在接口中去掉(隐藏) constructor(private _x:number,private _y:number){ this._x = _x; this._y = _y; } // setter set setY(value:number){ if (value < 0 ){ throw new Error('value 不能小于0') } this._y = value } // getter get getY(){ return this._y } public drawoPoint= () => { console.log('x',this._x,'y',this._y) }; getDistances= (p: IPoint)=>{ // 使用 getter return p.getY } } const point = new Point(20,80) point.setY = 100 point.drawoPoint() console.log(point.getDistances(point))
-
protected
:和private
类似,但是,protected
修饰的内容在派生类中可以访问