public:在类的内部和外部都可以访问
private:只能在类的内部进行访问
protected:可以在类的内部或继承类里进行访问,不能在外部访问
TypeScript将没有访问修饰符的成员都默认为public
//还是之前打电话的类,但是增加了一个验证记住的功能
class Phone{
constructor(owner : string)
{
this.owner = owner;
}
makeCall(ownerName : string, phoneNumber : string) : void
{
if(ownerName == this.owner) {//如果是机主,才运行打电话
console.log(this.owner, "make call to ", phoneNumber);
}
else{
console.log("Invalid owner, can't make call");
}
}
private owner : string; //定义为private,只能在类的内部进行访问
}
let aPhone= new Phone("XiaoMing");
aPhone.makeCall("XiaoMing", "12345"); //输出:XiaoMing make call to 12345
aPhone.makeCall("XiaoHong", "67890"); //输出:Invalid owner, can't make call
aPhone.owner = "XiaoHong"; //在类的外部无法对owner进行访问,输出:Property &