TypeScript 类的访问类型
类的访问类型基于三个关键
private protected public
class Person {
name: string;
}
const person = new Person();
person.name = "jspang.com";
console.log(person.name);
public 访问属性
public从英文字面的解释就是公共的或者说是公众的,在程序里的意思就是允许在类的内部和外部被调用.
如果不在类里对name的访问属性进行定义,那么它就会默认是public访问属性。
class Person {
public name:string;
public sayHello(){
console.log(this.name + 'say Hello')
}
}
//-------以下属于类的外部--------
const person = new Person()
person.name = 'jspang.com'
person.sayHello()
console.log(person.name)
private
只允许在类的内部调用不允许在外部调用
class Person {
private name:string;
public sayHello(){
console.log(this.name + 'say Hello') //此处不报错
}
}
//-------以下属于类的外部--------
const person = new Person()
person.name = 'jspang.com' //此处报错
person.sayHello()
console.log(person.name) //此处报错
protected 允许在类内及继承的子类中使用 */
class Person {
protected name:string;
public sayHello(){
console.log(this.name + 'say Hello') //此处不报错
}
}
class Teacher extends Person{
public sayBye(){
this.name; //此处不报错
}
}