TypeScript-封装

class People {
	private _name: string;
	age: number; 
	print() {
		return this._name + ":" + this.age + ":";
	}
    //加入封装,使外部可使用私有
    get name():string{
        return this._name;
    }
    set name(newName:string){
        this._name=newName;
        //可加判断
        if(newName =="aaa"){ 
        }else{ 
        }
    } 
}
let h = new People();
// h.name ="aaa";//Property 'name' is private and only accessible within class 'People'
//接口
h.name = "sss";
h.age = 19;
alert(h.print());
 

  

原文地址:https://www.cnblogs.com/allyh/p/10680132.html