class
需要先定义类型才能使用
class Person {public str: string;constructor() {this.str = '公有属性';}// 公有方法public pubFun() {console.log(this.str);}}
public
publuc 公有。如果不写默认是公有。
class Person {public str: string;str1:stringconstructor() {this.str = '公有属性';this.str1 = '公有'}// 公有方法public pubFun() {console.log(this.str);}pubFun1() {console.log(this.str1);}}
private
private 私有的,只能在自己内部使用,外部不能访问。子类中也无法使用
class Person {// 私有的变量private pri :string;constructor() {this.priFun(); // 私有的 只能自己使用}// 私有的方法private priFun(){console.log(this.pri);}}const p = new Person();// p.priFun(); // error
protectedprotected 私有的。只能自己使用或者在子类中使用
class Person {private pri:string;// 私有 但是在继承中可以使用protected pro :string;constructor() {this.pri = '私有,只能在自己类中使用';this.pro = '私有属性,在继承中可以使用';}private priFun(){console.log(this.pri);}protected proFun(){console.log(this.pro);}}class Xiao extends Person{get(){super.proFun()}NotGet(){super.priFun(); /// 属性“priFun”为私有属性,只能在类“Person”中访问。ts(2341)}}const p = new Person();p.proFun(); // 属性“proFun”受保护,只能在类“Person”及其子类中访问。ts(2445)p.priFun(); // 属性“priFun”为私有属性,只能在类“Person”中访问。ts(2341)const x = new Xiao();x.get();
readonly
readonly 只读不能修改
class Person {readonly read :string = '123';setRead(){this.read = '321' // 无法分配到 "read" ,因为它是只读属性。ts(2540)}}
